sql_ut_antlr4.cpp 335 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805
  1. #include "sql_ut_antlr4.h"
  2. #include "format/sql_format.h"
  3. #include "lexer/lexer.h"
  4. #include <yql/essentials/providers/common/provider/yql_provider_names.h>
  5. #include <yql/essentials/sql/sql.h>
  6. #include <util/generic/map.h>
  7. #include <library/cpp/testing/unittest/registar.h>
  8. #include <util/string/split.h>
  9. #include <format>
  10. using namespace NSQLTranslation;
  11. namespace {
  12. TParsedTokenList Tokenize(const TString& query) {
  13. auto lexer = NSQLTranslationV1::MakeLexer(true, true);
  14. TParsedTokenList tokens;
  15. NYql::TIssues issues;
  16. UNIT_ASSERT_C(Tokenize(*lexer, query, "Query", tokens, issues, SQL_MAX_PARSER_ERRORS),
  17. issues.ToString());
  18. return tokens;
  19. }
  20. TString ToString(const TParsedTokenList& tokens) {
  21. TStringBuilder reconstructedQuery;
  22. for (const auto& token : tokens) {
  23. if (token.Name == "WS" || token.Name == "EOF") {
  24. continue;
  25. }
  26. if (!reconstructedQuery.empty()) {
  27. reconstructedQuery << ' ';
  28. }
  29. reconstructedQuery << token.Content;
  30. }
  31. return reconstructedQuery;
  32. }
  33. }
  34. Y_UNIT_TEST_SUITE(AnsiMode) {
  35. Y_UNIT_TEST(PragmaAnsi) {
  36. UNIT_ASSERT(SqlToYql("PRAGMA ANSI 2016;").IsOk());
  37. }
  38. }
  39. Y_UNIT_TEST_SUITE(SqlParsingOnly) {
  40. ///This function is used in BACKWARD COMPATIBILITY tests below that LIMIT the sets of token that CAN NOT be used
  41. ///as identifiers in different contexts in a SQL request
  42. ///\return list of tokens that failed this check
  43. TVector<TString> ValidateTokens(const THashSet<TString>& forbidden, const std::function<TString (const TString& )>& makeRequest) {
  44. THashMap<TString, bool> allTokens;
  45. for (const auto& t: NSQLFormat::GetKeywords()) {
  46. allTokens[t] = !forbidden.contains((t));
  47. }
  48. for (const auto& f: forbidden) {
  49. UNIT_ASSERT(allTokens.contains(f)); //check that forbidden list contains tokens only(argument check)
  50. }
  51. TVector<TString> failed;
  52. for (const auto& [token, allowed]: allTokens) {
  53. if (SqlToYql(makeRequest(token)).IsOk() != allowed)
  54. failed.push_back(token);
  55. }
  56. return failed;
  57. }
  58. Y_UNIT_TEST(TokensAsColumnName) { //id_expr
  59. auto failed = ValidateTokens({
  60. "ALL", "ANY", "AS", "ASSUME", "ASYMMETRIC", "AUTOMAP", "BETWEEN", "BITCAST",
  61. "CALLABLE", "CASE", "CAST", "CUBE", "CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP",
  62. "DICT", "DISTINCT", "ENUM", "ERASE", "EXCEPT", "EXISTS", "FLOW", "FROM", "FULL", "GLOBAL",
  63. "HAVING", "HOP", "INTERSECT", "JSON_EXISTS", "JSON_QUERY", "JSON_VALUE", "LIMIT", "LIST", "LOCAL",
  64. "NOT", "OPTIONAL", "PROCESS", "REDUCE", "REPEATABLE", "RESOURCE", "RETURN", "RETURNING", "ROLLUP",
  65. "SELECT", "SET", "STREAM", "STRUCT", "SYMMETRIC", "TAGGED", "TUPLE", "UNBOUNDED",
  66. "UNION", "VARIANT", "WHEN", "WHERE", "WINDOW", "WITHOUT"
  67. },
  68. [](const TString& token){
  69. TStringBuilder req;
  70. req << "SELECT " << token << " FROM Plato.Input";
  71. return req;
  72. }
  73. );
  74. UNIT_ASSERT_VALUES_EQUAL(failed, TVector<TString>{});
  75. }
  76. Y_UNIT_TEST(TokensAsWithoutColumnName) { //id_without
  77. auto failed = ValidateTokens({
  78. "ALL", "AS", "ASSUME", "ASYMMETRIC", "AUTOMAP", "BETWEEN", "BITCAST",
  79. "CALLABLE", "CASE", "CAST", "CUBE", "CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP",
  80. "DICT", "DISTINCT", "EMPTY_ACTION", "ENUM", "EXCEPT", "EXISTS", "FALSE", "FLOW", "FROM", "FULL", "GLOBAL",
  81. "HAVING", "HOP", "INTERSECT", "JSON_EXISTS", "JSON_QUERY", "JSON_VALUE", "LIMIT", "LIST", "LOCAL",
  82. "NOT", "NULL", "OPTIONAL", "PROCESS", "REDUCE", "REPEATABLE", "RESOURCE", "RETURN", "RETURNING", "ROLLUP",
  83. "SELECT", "SET", "STRUCT", "SYMMETRIC", "TAGGED", "TRUE", "TUPLE", "UNBOUNDED",
  84. "UNION", "VARIANT", "WHEN", "WHERE", "WINDOW", "WITHOUT"
  85. },
  86. [](const TString& token){
  87. TStringBuilder req;
  88. req << "SELECT * WITHOUT " << token << " FROM Plato.Input";
  89. return req;
  90. }
  91. );
  92. UNIT_ASSERT_VALUES_EQUAL(failed, TVector<TString>{});
  93. }
  94. Y_UNIT_TEST(TokensAsColumnNameInAddColumn) { //id_schema
  95. auto failed = ValidateTokens({
  96. "ANY", "AUTOMAP", "CALLABLE", "COLUMN", "DICT", "ENUM", "ERASE", "FALSE", "FLOW",
  97. "GLOBAL", "LIST", "OPTIONAL", "REPEATABLE", "RESOURCE",
  98. "SET", "STREAM", "STRUCT", "TAGGED", "TRUE", "TUPLE", "VARIANT"
  99. },
  100. [](const TString& token){
  101. TStringBuilder req;
  102. req << "ALTER TABLE Plato.Input ADD COLUMN " << token << " Bool";
  103. return req;
  104. }
  105. );
  106. UNIT_ASSERT_VALUES_EQUAL(failed, TVector<TString>{});
  107. }
  108. Y_UNIT_TEST(TokensAsColumnAlias) {
  109. auto failed = ValidateTokens({
  110. "AUTOMAP", "FALSE",
  111. "GLOBAL", "REPEATABLE", "TRUE"
  112. },
  113. [](const TString& token){
  114. TStringBuilder req;
  115. req << "SELECT Col as " << token << " FROM Plato.Input";
  116. return req;
  117. }
  118. );
  119. UNIT_ASSERT_VALUES_EQUAL(failed, TVector<TString>{});
  120. }
  121. Y_UNIT_TEST(TokensAsTableName) { //id_table_or_type
  122. auto failed = ValidateTokens({
  123. "ANY", "AUTOMAP", "COLUMN", "ERASE", "FALSE",
  124. "GLOBAL", "REPEATABLE", "STREAM", "TRUE"
  125. },
  126. [](const TString& token){
  127. TStringBuilder req;
  128. req << "SELECT * FROM Plato." << token;
  129. return req;
  130. }
  131. );
  132. UNIT_ASSERT_VALUES_EQUAL(failed, TVector<TString>{});
  133. }
  134. Y_UNIT_TEST(TokensAsTableAlias) { //id_table
  135. auto failed = ValidateTokens({
  136. "AUTOMAP", "CALLABLE", "DICT", "ENUM","FALSE", "FLOW",
  137. "GLOBAL", "LIST", "OPTIONAL", "REPEATABLE", "RESOURCE",
  138. "SET", "STRUCT", "TAGGED", "TRUE", "TUPLE", "VARIANT"
  139. },
  140. [](const TString& token){
  141. TStringBuilder req;
  142. req << "SELECT * FROM Plato.Input AS " << token;
  143. return req;
  144. }
  145. );
  146. UNIT_ASSERT_VALUES_EQUAL(failed, TVector<TString>{});
  147. }
  148. Y_UNIT_TEST(TokensAsHints) { //id_hint
  149. auto failed = ValidateTokens({
  150. "AUTOMAP", "CALLABLE", "COLUMNS", "DICT", "ENUM", "FALSE", "FLOW",
  151. "GLOBAL", "LIST", "OPTIONAL", "REPEATABLE", "RESOURCE",
  152. "SCHEMA", "SET", "STRUCT", "TAGGED", "TRUE", "TUPLE", "VARIANT"
  153. },
  154. [](const TString& token){
  155. TStringBuilder req;
  156. req << "SELECT * FROM Plato.Input WITH " << token;
  157. return req;
  158. }
  159. );
  160. UNIT_ASSERT_VALUES_EQUAL(failed, TVector<TString>{});
  161. }
  162. Y_UNIT_TEST(TokensAsWindow) { //id_window
  163. auto failed = ValidateTokens({
  164. "AUTOMAP", "CALLABLE", "DICT", "ENUM", "FALSE", "FLOW", "GLOBAL", "GROUPS", "LIST", "OPTIONAL",
  165. "RANGE", "REPEATABLE", "RESOURCE", "ROWS", "SET", "STRUCT", "TAGGED" ,"TRUE", "TUPLE", "VARIANT"
  166. },
  167. [](const TString& token){
  168. TStringBuilder req;
  169. req << "SELECT * FROM Plato.Input WINDOW " << token << " AS ()";
  170. return req;
  171. }
  172. );
  173. UNIT_ASSERT_VALUES_EQUAL(failed, TVector<TString>{});
  174. }
  175. Y_UNIT_TEST(TokensAsIdExprIn) { //id_expr_in
  176. auto failed = ValidateTokens({
  177. "ALL", "ANY", "AS", "ASSUME", "ASYMMETRIC", "AUTOMAP", "BETWEEN", "BITCAST",
  178. "CALLABLE", "CASE", "CAST", "COMPACT", "CUBE", "CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP",
  179. "DICT", "DISTINCT", "ENUM", "ERASE", "EXCEPT", "EXISTS", "FLOW", "FROM", "FULL", "GLOBAL",
  180. "HAVING", "HOP", "INTERSECT", "JSON_EXISTS", "JSON_QUERY", "JSON_VALUE", "LIMIT", "LIST", "LOCAL",
  181. "NOT", "OPTIONAL", "PROCESS", "REDUCE", "REPEATABLE", "RESOURCE", "RETURN", "RETURNING", "ROLLUP",
  182. "SELECT", "SET", "STREAM", "STRUCT", "SYMMETRIC", "TAGGED", "TUPLE", "UNBOUNDED",
  183. "UNION", "VARIANT", "WHEN", "WHERE", "WINDOW", "WITHOUT"
  184. },
  185. [](const TString& token){
  186. TStringBuilder req;
  187. req << "SELECT * FROM Plato.Input WHERE q IN " << token;
  188. return req;
  189. }
  190. );
  191. UNIT_ASSERT_VALUES_EQUAL(failed, TVector<TString>{});
  192. }
  193. Y_UNIT_TEST(TableHints) {
  194. UNIT_ASSERT(SqlToYql("SELECT * FROM plato.Input WITH INFER_SCHEMA").IsOk());
  195. UNIT_ASSERT(SqlToYql("SELECT * FROM plato.Input WITH (INFER_SCHEMA)").IsOk());
  196. }
  197. Y_UNIT_TEST(InNoHints) {
  198. TString query = "SELECT * FROM plato.Input WHERE key IN (1,2,3)";
  199. VerifySqlInHints(query, { "'('('warnNoAnsi))" }, {});
  200. VerifySqlInHints(query, { "'()" }, false);
  201. VerifySqlInHints(query, { "'('('ansi))" }, true);
  202. }
  203. Y_UNIT_TEST(InHintCompact) {
  204. // should parse COMPACT as hint
  205. TString query = "SELECT * FROM plato.Input WHERE key IN COMPACT(1, 2, 3)";
  206. VerifySqlInHints(query, { "'('isCompact)" });
  207. }
  208. Y_UNIT_TEST(InHintSubquery) {
  209. // should parse tableSource as hint
  210. TString query = "$subq = (SELECT key FROM plato.Input); SELECT * FROM plato.Input WHERE key IN $subq";
  211. VerifySqlInHints(query, { "'('tableSource)" });
  212. }
  213. Y_UNIT_TEST(InHintCompactSubquery) {
  214. TString query = "$subq = (SELECT key FROM plato.Input); SELECT * FROM plato.Input WHERE key IN COMPACT $subq";
  215. VerifySqlInHints(query, { "'('isCompact)", "'('tableSource)" });
  216. }
  217. Y_UNIT_TEST(CompactKeywordNotReservedForNames) {
  218. UNIT_ASSERT(SqlToYql("SELECT COMPACT FROM plato.Input WHERE COMPACT IN COMPACT(1, 2, 3)").IsOk());
  219. UNIT_ASSERT(SqlToYql("USE plato; SELECT * FROM COMPACT").IsOk());
  220. }
  221. Y_UNIT_TEST(FamilyKeywordNotReservedForNames) {
  222. // FIXME: check if we can get old behaviour
  223. //UNIT_ASSERT(SqlToYql("USE plato; CREATE TABLE FAMILY (FAMILY Uint32, PRIMARY KEY (FAMILY));").IsOk());
  224. //UNIT_ASSERT(SqlToYql("USE plato; SELECT FAMILY FROM FAMILY").IsOk());
  225. UNIT_ASSERT(SqlToYql("USE plato; SELECT FAMILY FROM Input").IsOk());
  226. }
  227. Y_UNIT_TEST(ResetKeywordNotReservedForNames) {
  228. UNIT_ASSERT(SqlToYql("USE plato; CREATE TABLE RESET (RESET Uint32, PRIMARY KEY (RESET));").IsOk());
  229. UNIT_ASSERT(SqlToYql("USE plato; SELECT RESET FROM RESET").IsOk());
  230. }
  231. Y_UNIT_TEST(SyncKeywordNotReservedForNames) {
  232. UNIT_ASSERT(SqlToYql("USE plato; CREATE TABLE SYNC (SYNC Uint32, PRIMARY KEY (SYNC));").IsOk());
  233. UNIT_ASSERT(SqlToYql("USE plato; SELECT SYNC FROM SYNC").IsOk());
  234. }
  235. Y_UNIT_TEST(AsyncKeywordNotReservedForNames) {
  236. UNIT_ASSERT(SqlToYql("USE plato; CREATE TABLE ASYNC (ASYNC Uint32, PRIMARY KEY (ASYNC));").IsOk());
  237. UNIT_ASSERT(SqlToYql("USE plato; SELECT ASYNC FROM ASYNC").IsOk());
  238. }
  239. Y_UNIT_TEST(DisableKeywordNotReservedForNames) {
  240. UNIT_ASSERT(SqlToYql("USE plato; CREATE TABLE DISABLE (DISABLE Uint32, PRIMARY KEY (DISABLE));").IsOk());
  241. UNIT_ASSERT(SqlToYql("USE plato; SELECT DISABLE FROM DISABLE").IsOk());
  242. }
  243. Y_UNIT_TEST(ChangefeedKeywordNotReservedForNames) {
  244. UNIT_ASSERT(SqlToYql("USE plato; CREATE TABLE CHANGEFEED (CHANGEFEED Uint32, PRIMARY KEY (CHANGEFEED));").IsOk());
  245. UNIT_ASSERT(SqlToYql("USE plato; SELECT CHANGEFEED FROM CHANGEFEED").IsOk());
  246. }
  247. Y_UNIT_TEST(ReplicationKeywordNotReservedForNames) {
  248. UNIT_ASSERT(SqlToYql("USE plato; CREATE TABLE REPLICATION (REPLICATION Uint32, PRIMARY KEY (REPLICATION));").IsOk());
  249. UNIT_ASSERT(SqlToYql("USE plato; SELECT REPLICATION FROM REPLICATION").IsOk());
  250. }
  251. Y_UNIT_TEST(SecondsKeywordNotReservedForNames) {
  252. UNIT_ASSERT(SqlToYql("USE plato; CREATE TABLE SECONDS (SECONDS Uint32, PRIMARY KEY (SECONDS));").IsOk());
  253. UNIT_ASSERT(SqlToYql("USE plato; SELECT SECONDS FROM SECONDS").IsOk());
  254. }
  255. Y_UNIT_TEST(MillisecondsKeywordNotReservedForNames) {
  256. UNIT_ASSERT(SqlToYql("USE plato; CREATE TABLE MILLISECONDS (MILLISECONDS Uint32, PRIMARY KEY (MILLISECONDS));").IsOk());
  257. UNIT_ASSERT(SqlToYql("USE plato; SELECT MILLISECONDS FROM MILLISECONDS").IsOk());
  258. }
  259. Y_UNIT_TEST(MicrosecondsKeywordNotReservedForNames) {
  260. UNIT_ASSERT(SqlToYql("USE plato; CREATE TABLE MICROSECONDS (MICROSECONDS Uint32, PRIMARY KEY (MICROSECONDS));").IsOk());
  261. UNIT_ASSERT(SqlToYql("USE plato; SELECT MICROSECONDS FROM MICROSECONDS").IsOk());
  262. }
  263. Y_UNIT_TEST(NanosecondsKeywordNotReservedForNames) {
  264. UNIT_ASSERT(SqlToYql("USE plato; CREATE TABLE NANOSECONDS (NANOSECONDS Uint32, PRIMARY KEY (NANOSECONDS));").IsOk());
  265. UNIT_ASSERT(SqlToYql("USE plato; SELECT NANOSECONDS FROM NANOSECONDS").IsOk());
  266. }
  267. Y_UNIT_TEST(Jubilee) {
  268. NYql::TAstParseResult res = SqlToYql("USE plato; INSERT INTO Arcadia (r2000000) VALUES (\"2M GET!!!\");");
  269. UNIT_ASSERT(res.Root);
  270. }
  271. Y_UNIT_TEST(QualifiedAsteriskBefore) {
  272. NYql::TAstParseResult res = SqlToYql(
  273. "PRAGMA DisableSimpleColumns;"
  274. "select interested_table.*, LENGTH(value) AS megahelpful_len from plato.Input as interested_table;"
  275. );
  276. UNIT_ASSERT(res.Root);
  277. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  278. static bool seenStar = false;
  279. if (word == "FlattenMembers") {
  280. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("interested_table."));
  281. } else if (word == "SqlProjectItem") {
  282. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(Quote("megahelpful_len")));
  283. UNIT_ASSERT_VALUES_EQUAL(seenStar, true);
  284. } else if (word == "SqlProjectStarItem") {
  285. seenStar = true;
  286. }
  287. };
  288. TWordCountHive elementStat = {{TString("FlattenMembers"), 0}, {TString("SqlProjectItem"), 0}, {TString("SqlProjectStarItem"), 0}};
  289. VerifyProgram(res, elementStat, verifyLine);
  290. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["FlattenMembers"]);
  291. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["SqlProjectItem"]);
  292. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["SqlProjectStarItem"]);
  293. }
  294. Y_UNIT_TEST(QualifiedAsteriskAfter) {
  295. NYql::TAstParseResult res = SqlToYql(
  296. "PRAGMA DisableSimpleColumns;"
  297. "select LENGTH(value) AS megahelpful_len, interested_table.* from plato.Input as interested_table;"
  298. );
  299. UNIT_ASSERT(res.Root);
  300. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  301. static bool seenStar = false;
  302. if (word == "FlattenMembers") {
  303. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("interested_table."));
  304. } else if (word == "SqlProjectItem") {
  305. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(Quote("megahelpful_len")));
  306. UNIT_ASSERT_VALUES_EQUAL(seenStar, false);
  307. } else if (word == "SqlProjectStarItem") {
  308. seenStar = true;
  309. }
  310. };
  311. TWordCountHive elementStat = {{TString("FlattenMembers"), 0}, {TString("SqlProjectItem"), 0}, {TString("SqlProjectStarItem"), 0}};
  312. VerifyProgram(res, elementStat, verifyLine);
  313. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["FlattenMembers"]);
  314. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["SqlProjectItem"]);
  315. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["SqlProjectStarItem"]);
  316. }
  317. Y_UNIT_TEST(QualifiedMembers) {
  318. NYql::TAstParseResult res = SqlToYql("select interested_table.key, interested_table.value from plato.Input as interested_table;");
  319. UNIT_ASSERT(res.Root);
  320. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  321. const bool fieldKey = TString::npos != line.find(Quote("key"));
  322. const bool fieldValue = TString::npos != line.find(Quote("value"));
  323. const bool refOnTable = TString::npos != line.find("interested_table.");
  324. if (word == "SqlProjectItem") {
  325. UNIT_ASSERT(fieldKey || fieldValue);
  326. UNIT_ASSERT(!refOnTable);
  327. } else if (word == "Write!") {
  328. UNIT_ASSERT(fieldKey && fieldValue && !refOnTable);
  329. }
  330. };
  331. TWordCountHive elementStat = {{TString("SqlProjectStarItem"), 0}, {TString("SqlProjectItem"), 0}, {TString("Write!"), 0}};
  332. VerifyProgram(res, elementStat, verifyLine);
  333. UNIT_ASSERT_VALUES_EQUAL(0, elementStat["SqlProjectStarItem"]);
  334. UNIT_ASSERT_VALUES_EQUAL(2, elementStat["SqlProjectItem"]);
  335. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write!"]);
  336. }
  337. Y_UNIT_TEST(ExplainQueryPlan) {
  338. UNIT_ASSERT(SqlToYql("EXPLAIN SELECT 1;").IsOk());
  339. UNIT_ASSERT(SqlToYql("EXPLAIN QUERY PLAN SELECT 1;").IsOk());
  340. }
  341. Y_UNIT_TEST(JoinParseCorrect) {
  342. NYql::TAstParseResult res = SqlToYql(
  343. "PRAGMA DisableSimpleColumns;"
  344. " SELECT table_bb.*, table_aa.key as megakey"
  345. " FROM plato.Input AS table_aa"
  346. " JOIN plato.Input AS table_bb"
  347. " ON table_aa.value == table_bb.value;"
  348. );
  349. UNIT_ASSERT(res.Root);
  350. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  351. if (word == "SelectMembers") {
  352. UNIT_ASSERT_VALUES_EQUAL(TString::npos, line.find("table_aa."));
  353. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("table_bb."));
  354. } else if (word == "SqlProjectItem") {
  355. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(Quote("megakey")));
  356. } else if (word == "SqlColumn") {
  357. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(Quote("table_aa")));
  358. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(Quote("key")));
  359. }
  360. };
  361. TWordCountHive elementStat = {{TString("SqlProjectItem"), 0}, {TString("SqlProjectStarItem"), 0}, {TString("SelectMembers"), 0}, {TString("SqlColumn"), 0}};
  362. VerifyProgram(res, elementStat, verifyLine);
  363. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["SqlProjectItem"]);
  364. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["SqlProjectStarItem"]);
  365. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["SelectMembers"]);
  366. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["SqlColumn"]);
  367. }
  368. Y_UNIT_TEST(Join3Table) {
  369. NYql::TAstParseResult res = SqlToYql(
  370. " PRAGMA DisableSimpleColumns;"
  371. " SELECT table_bb.*, table_aa.key as gigakey, table_cc.* "
  372. " FROM plato.Input AS table_aa"
  373. " JOIN plato.Input AS table_bb ON table_aa.key == table_bb.key"
  374. " JOIN plato.Input AS table_cc ON table_aa.subkey == table_cc.subkey;"
  375. );
  376. Err2Str(res);
  377. UNIT_ASSERT(res.Root);
  378. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  379. if (word == "SelectMembers") {
  380. UNIT_ASSERT_VALUES_EQUAL(TString::npos, line.find("table_aa."));
  381. UNIT_ASSERT(line.find("table_bb.") != TString::npos || line.find("table_cc.") != TString::npos);
  382. } else if (word == "SqlProjectItem") {
  383. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(Quote("gigakey")));
  384. } else if (word == "SqlColumn") {
  385. const auto posTableAA = line.find(Quote("table_aa"));
  386. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, posTableAA);
  387. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(Quote("key")));
  388. UNIT_ASSERT_VALUES_EQUAL(TString::npos, line.find("table_aa", posTableAA + 3));
  389. }
  390. };
  391. TWordCountHive elementStat = {{TString("SqlProjectItem"), 0}, {TString("SqlProjectStarItem"), 0}, {TString("SelectMembers"), 0}, {TString("SqlColumn"), 0}};
  392. VerifyProgram(res, elementStat, verifyLine);
  393. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["SqlProjectItem"]);
  394. UNIT_ASSERT_VALUES_EQUAL(2, elementStat["SqlProjectStarItem"]);
  395. UNIT_ASSERT_VALUES_EQUAL(2, elementStat["SelectMembers"]);
  396. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["SqlColumn"]);
  397. }
  398. Y_UNIT_TEST(DisabledJoinCartesianProduct) {
  399. NYql::TAstParseResult res = SqlToYql("pragma DisableAnsiImplicitCrossJoin; use plato; select * from A,B,C");
  400. UNIT_ASSERT(!res.Root);
  401. UNIT_ASSERT_STRINGS_EQUAL(res.Issues.ToString(), "<main>:1:67: Error: Cartesian product of tables is disabled. Please use explicit CROSS JOIN or enable it via PRAGMA AnsiImplicitCrossJoin\n");
  402. }
  403. Y_UNIT_TEST(JoinCartesianProduct) {
  404. NYql::TAstParseResult res = SqlToYql("pragma AnsiImplicitCrossJoin; use plato; select * from A,B,C");
  405. UNIT_ASSERT(res.Root);
  406. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  407. if (word == "EquiJoin") {
  408. auto pos = line.find("Cross");
  409. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, pos);
  410. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("Cross", pos + 1));
  411. }
  412. };
  413. TWordCountHive elementStat = {{TString("EquiJoin"), 0}};
  414. VerifyProgram(res, elementStat, verifyLine);
  415. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["EquiJoin"]);
  416. }
  417. Y_UNIT_TEST(JoinWithoutConcreteColumns) {
  418. NYql::TAstParseResult res = SqlToYql(
  419. " use plato;"
  420. " SELECT a.v, b.value"
  421. " FROM `Input1` VIEW `ksv` AS a"
  422. " JOIN `Input2` AS b"
  423. " ON a.k == b.key;"
  424. );
  425. UNIT_ASSERT(res.Root);
  426. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  427. if (word == "SqlProjectItem") {
  428. UNIT_ASSERT(line.find(Quote("a.v")) != TString::npos || line.find(Quote("b.value")) != TString::npos);
  429. } else if (word == "SqlColumn") {
  430. const auto posTableA = line.find(Quote("a"));
  431. const auto posTableB = line.find(Quote("b"));
  432. if (posTableA != TString::npos) {
  433. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(Quote("v")));
  434. } else {
  435. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, posTableB);
  436. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(Quote("value")));
  437. }
  438. }
  439. };
  440. TWordCountHive elementStat = {{TString("SqlProjectStarItem"), 0}, {TString("SqlProjectItem"), 0}, {TString("SqlColumn"), 0}};
  441. VerifyProgram(res, elementStat, verifyLine);
  442. UNIT_ASSERT_VALUES_EQUAL(0, elementStat["SqlProjectStarItem"]);
  443. UNIT_ASSERT_VALUES_EQUAL(2, elementStat["SqlProjectItem"]);
  444. UNIT_ASSERT_VALUES_EQUAL(2, elementStat["SqlColumn"]);
  445. }
  446. Y_UNIT_TEST(JoinWithSameValues) {
  447. NYql::TAstParseResult res = SqlToYql("SELECT a.value, b.value FROM plato.Input AS a JOIN plato.Input as b ON a.key == b.key;");
  448. UNIT_ASSERT(res.Root);
  449. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  450. if (word == "SqlProjectItem") {
  451. const bool isValueFromA = TString::npos != line.find(Quote("a.value"));
  452. const bool isValueFromB = TString::npos != line.find(Quote("b.value"));
  453. UNIT_ASSERT(isValueFromA || isValueFromB);
  454. } if (word == "Write!") {
  455. UNIT_ASSERT_VALUES_EQUAL(TString::npos, line.find("a.a."));
  456. UNIT_ASSERT_VALUES_EQUAL(TString::npos, line.find("b.b."));
  457. }
  458. };
  459. TWordCountHive elementStat = {{TString("SqlProjectStarItem"), 0}, {TString("SqlProjectItem"), 0}, {"Write!", 0}};
  460. VerifyProgram(res, elementStat, verifyLine);
  461. UNIT_ASSERT_VALUES_EQUAL(0, elementStat["SqlProjectStarItem"]);
  462. UNIT_ASSERT_VALUES_EQUAL(2, elementStat["SqlProjectItem"]);
  463. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write!"]);
  464. }
  465. Y_UNIT_TEST(SameColumnsForDifferentTables) {
  466. NYql::TAstParseResult res = SqlToYql("SELECT a.key, b.key FROM plato.Input as a JOIN plato.Input as b on a.key==b.key;");
  467. UNIT_ASSERT(res.Root);
  468. }
  469. Y_UNIT_TEST(SameColumnsForDifferentTablesFullJoin) {
  470. NYql::TAstParseResult res = SqlToYql("SELECT a.key, b.key, a.value, b.value FROM plato.Input AS a FULL JOIN plato.Input AS b USING(key);");
  471. UNIT_ASSERT(res.Root);
  472. }
  473. Y_UNIT_TEST(JoinStreamLookupStrategyHint) {
  474. {
  475. NYql::TAstParseResult res = SqlToYql("SELECT * FROM plato.Input AS a JOIN /*+ StreamLookup() */ plato.Input AS b USING(key);");
  476. UNIT_ASSERT(res.Root);
  477. }
  478. //case insensitive
  479. {
  480. NYql::TAstParseResult res = SqlToYql("SELECT * FROM plato.Input AS a JOIN /*+ streamlookup() */ plato.Input AS b USING(key);");
  481. UNIT_ASSERT(res.Root);
  482. }
  483. }
  484. Y_UNIT_TEST(JoinConflictingStrategyHint) {
  485. {
  486. NYql::TAstParseResult res = SqlToYql("SELECT * FROM plato.Input AS a JOIN /*+ StreamLookup() */ /*+ Merge() */ plato.Input AS b USING(key);");
  487. UNIT_ASSERT(!res.Root);
  488. UNIT_ASSERT_STRINGS_EQUAL(res.Issues.ToString(), "<main>:1:91: Error: Conflicting join strategy hints\n");
  489. }
  490. }
  491. Y_UNIT_TEST(JoinDuplicatingStrategyHint) {
  492. {
  493. NYql::TAstParseResult res = SqlToYql("SELECT * FROM plato.Input AS a JOIN /*+ StreamLookup() */ /*+ StreamLookup() */ plato.Input AS b USING(key);");
  494. UNIT_ASSERT(!res.Root);
  495. UNIT_ASSERT_STRINGS_EQUAL(res.Issues.ToString(), "<main>:1:98: Error: Duplicate join strategy hint\n");
  496. }
  497. }
  498. Y_UNIT_TEST(WarnCrossJoinStrategyHint) {
  499. NYql::TAstParseResult res = SqlToYql("SELECT * FROM plato.Input AS a CROSS JOIN /*+ merge() */ plato.Input AS b;");
  500. UNIT_ASSERT(res.Root);
  501. UNIT_ASSERT_STRINGS_EQUAL(res.Issues.ToString(), "<main>:1:32: Warning: Non-default join strategy will not be used for CROSS JOIN, code: 4534\n");
  502. }
  503. Y_UNIT_TEST(WarnCartesianProductStrategyHint) {
  504. NYql::TAstParseResult res = SqlToYql("pragma AnsiImplicitCrossJoin; use plato; SELECT * FROM A, /*+ merge() */ B;");
  505. UNIT_ASSERT(res.Root);
  506. UNIT_ASSERT_STRINGS_EQUAL(res.Issues.ToString(), "<main>:1:74: Warning: Non-default join strategy will not be used for CROSS JOIN, code: 4534\n");
  507. }
  508. Y_UNIT_TEST(WarnUnknownJoinStrategyHint) {
  509. NYql::TAstParseResult res = SqlToYql("SELECT * FROM plato.Input AS a JOIN /*+ xmerge() */ plato.Input AS b USING (key);");
  510. UNIT_ASSERT(res.Root);
  511. UNIT_ASSERT_STRINGS_EQUAL(res.Issues.ToString(), "<main>:1:41: Warning: Unsupported join hint: xmerge, code: 4534\n");
  512. }
  513. Y_UNIT_TEST(ReverseLabels) {
  514. NYql::TAstParseResult res = SqlToYql("select in.key as subkey, subkey as key from plato.Input as in;");
  515. UNIT_ASSERT(res.Root);
  516. }
  517. Y_UNIT_TEST(AutogenerationAliasWithoutCollisionConflict1) {
  518. NYql::TAstParseResult res = SqlToYql("select LENGTH(Value), key as column1 from plato.Input;");
  519. UNIT_ASSERT(res.Root);
  520. }
  521. Y_UNIT_TEST(AutogenerationAliasWithoutCollision2Conflict2) {
  522. NYql::TAstParseResult res = SqlToYql("select key as column0, LENGTH(Value) from plato.Input;");
  523. UNIT_ASSERT(res.Root);
  524. }
  525. Y_UNIT_TEST(InputAliasForQualifiedAsterisk) {
  526. NYql::TAstParseResult res = SqlToYql("use plato; select zyuzya.*, key from plato.Input as zyuzya;");
  527. UNIT_ASSERT(res.Root);
  528. }
  529. Y_UNIT_TEST(SelectSupportsResultColumnsWithTrailingComma) {
  530. NYql::TAstParseResult res = SqlToYql("select a, b, c, from plato.Input;");
  531. UNIT_ASSERT(res.Root);
  532. }
  533. Y_UNIT_TEST(SelectOrderByLabeledColumn) {
  534. NYql::TAstParseResult res = SqlToYql("pragma DisableOrderedColumns; select key as goal from plato.Input order by goal");
  535. UNIT_ASSERT(res.Root);
  536. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  537. if (word == "DataSource") {
  538. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("plato"));
  539. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("Input"));
  540. UNIT_ASSERT_VALUES_EQUAL(TString::npos, line.find("goal"));
  541. } else if (word == "Sort") {
  542. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("goal"));
  543. UNIT_ASSERT_VALUES_EQUAL(TString::npos, line.find("key"));
  544. }
  545. };
  546. TWordCountHive elementStat = {{TString("DataSource"), 0}, {TString("Sort"), 0}};
  547. VerifyProgram(res, elementStat, verifyLine);
  548. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["DataSource"]);
  549. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Sort"]);
  550. }
  551. Y_UNIT_TEST(SelectOrderBySimpleExpr) {
  552. NYql::TAstParseResult res = SqlToYql("select a from plato.Input order by a + a");
  553. UNIT_ASSERT(res.Root);
  554. }
  555. Y_UNIT_TEST(SelectAssumeOrderByTableRowAccess) {
  556. NYql::TAstParseResult res = SqlToYql("$key = 'foo';select * from plato.Input assume order by TableRow().$key");
  557. UNIT_ASSERT(res.Root);
  558. }
  559. Y_UNIT_TEST(SelectOrderByDuplicateLabels) {
  560. NYql::TAstParseResult res = SqlToYql("select a from plato.Input order by a, a");
  561. UNIT_ASSERT(res.Root);
  562. }
  563. Y_UNIT_TEST(SelectOrderByExpression) {
  564. NYql::TAstParseResult res = SqlToYql("select * from plato.Input as i order by cast(key as uint32) + cast(subkey as uint32)");
  565. UNIT_ASSERT(res.Root);
  566. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  567. if (word == "Sort") {
  568. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("\"+MayWarn\""));
  569. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("key"));
  570. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("subkey"));
  571. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("(Bool 'true)"));
  572. UNIT_ASSERT_VALUES_EQUAL(TString::npos, line.find("i.key"));
  573. UNIT_ASSERT_VALUES_EQUAL(TString::npos, line.find("i.subkey"));
  574. }
  575. };
  576. TWordCountHive elementStat = {{TString("Sort"), 0}};
  577. VerifyProgram(res, elementStat, verifyLine);
  578. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Sort"]);
  579. }
  580. Y_UNIT_TEST(SelectOrderByExpressionDesc) {
  581. NYql::TAstParseResult res = SqlToYql("pragma disablesimplecolumns; select i.*, key, subkey from plato.Input as i order by cast(i.key as uint32) - cast(i.subkey as uint32) desc");
  582. UNIT_ASSERT(res.Root);
  583. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  584. if (word == "Sort") {
  585. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("\"-MayWarn\""));
  586. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("\"key\""));
  587. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("\"subkey\""));
  588. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("(Bool 'false)"));
  589. } else if (word == "Write!") {
  590. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("'columns"));
  591. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("\"key\""));
  592. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("\"subkey\""));
  593. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("prefix"));
  594. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("\"i.\""));
  595. }
  596. };
  597. TWordCountHive elementStat = {{TString("Sort"), 0}, {TString("Write!"), 0}};
  598. VerifyProgram(res, elementStat, verifyLine);
  599. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Sort"]);
  600. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write!"]);
  601. }
  602. Y_UNIT_TEST(SelectOrderByExpressionAsc) {
  603. NYql::TAstParseResult res = SqlToYql("select i.key, i.subkey from plato.Input as i order by cast(key as uint32) % cast(i.subkey as uint32) asc");
  604. UNIT_ASSERT(res.Root);
  605. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  606. if (word == "Sort") {
  607. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("\"%MayWarn\""));
  608. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("\"key\""));
  609. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("\"subkey\""));
  610. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("(Bool 'true)"));
  611. } else if (word == "Write!") {
  612. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("'columns"));
  613. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("\"key\""));
  614. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("\"subkey\""));
  615. UNIT_ASSERT_VALUES_EQUAL(TString::npos, line.find("i."));
  616. }
  617. };
  618. TWordCountHive elementStat = {{TString("Sort"), 0}, {TString("Write!"), 0}};
  619. VerifyProgram(res, elementStat, verifyLine);
  620. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Sort"]);
  621. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write!"]);
  622. }
  623. Y_UNIT_TEST(ReferenceToKeyInSubselect) {
  624. NYql::TAstParseResult res = SqlToYql("select b.key from (select a.key from plato.Input as a) as b;");
  625. UNIT_ASSERT(res.Root);
  626. }
  627. Y_UNIT_TEST(OrderByCastValue) {
  628. NYql::TAstParseResult res = SqlToYql("select i.key, i.subkey from plato.Input as i order by cast(key as uint32) desc;");
  629. UNIT_ASSERT(res.Root);
  630. }
  631. Y_UNIT_TEST(GroupByCastValue) {
  632. NYql::TAstParseResult res = SqlToYql("select count(1) from plato.Input as i group by cast(key as uint8);");
  633. UNIT_ASSERT(res.Root);
  634. }
  635. Y_UNIT_TEST(KeywordInSelectColumns) {
  636. NYql::TAstParseResult res = SqlToYql("select in, s.check from (select 1 as in, \"test\" as check) as s;");
  637. UNIT_ASSERT(res.Root);
  638. }
  639. Y_UNIT_TEST(SelectAllGroupBy) {
  640. NYql::TAstParseResult res = SqlToYql("select * from plato.Input group by subkey;");
  641. UNIT_ASSERT(res.Root);
  642. }
  643. Y_UNIT_TEST(CreateObjectWithFeatures) {
  644. NYql::TAstParseResult res = SqlToYql("USE plato; CREATE OBJECT secretId (TYPE SECRET) WITH (Key1=Value1, K2=V2);");
  645. UNIT_ASSERT(res.Root);
  646. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  647. if (word == "Write") {
  648. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("'('\"K2\" '\"V2\") '('\"Key1\" '\"Value1\")"));
  649. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("createObject"));
  650. }
  651. };
  652. TWordCountHive elementStat = { {TString("Write"), 0}, {TString("SECRET"), 0} };
  653. VerifyProgram(res, elementStat, verifyLine);
  654. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  655. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["SECRET"]);
  656. }
  657. Y_UNIT_TEST(CreateObjectIfNotExists) {
  658. NYql::TAstParseResult res = SqlToYql("USE plato; CREATE OBJECT IF NOT EXISTS secretId (TYPE SECRET) WITH (Key1=Value1, K2=V2);");
  659. UNIT_ASSERT(res.Root);
  660. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  661. if (word == "Write") {
  662. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("createObjectIfNotExists"));
  663. }
  664. };
  665. TWordCountHive elementStat = { {TString("Write"), 0}, {TString("SECRET"), 0} };
  666. VerifyProgram(res, elementStat, verifyLine);
  667. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  668. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["SECRET"]);
  669. }
  670. Y_UNIT_TEST(CreateObjectWithFeaturesStrings) {
  671. NYql::TAstParseResult res = SqlToYql("USE plato; CREATE OBJECT secretId (TYPE SECRET) WITH (Key1=\"Value1\", K2='V2', K3=V3, K4='', K5=`aaa`, K6='a\\'aa');");
  672. UNIT_ASSERT(res.Root);
  673. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  674. if (word == "Write") {
  675. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("'('\"K2\" '\"V2\") '('\"K3\" '\"V3\") '('\"K4\" '\"\") '('\"K5\" '\"aaa\") '('\"K6\" '\"a'aa\") '('\"Key1\" '\"Value1\")"));
  676. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("createObject"));
  677. }
  678. };
  679. TWordCountHive elementStat = {{TString("Write"), 0}, {TString("SECRET"), 0}};
  680. VerifyProgram(res, elementStat, verifyLine);
  681. }
  682. Y_UNIT_TEST(UpsertObjectWithFeatures) {
  683. NYql::TAstParseResult res = SqlToYql("USE plato; UPSERT OBJECT secretId (TYPE SECRET) WITH (Key1=Value1, K2=V2);");
  684. UNIT_ASSERT(res.Root);
  685. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  686. if (word == "Write") {
  687. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("'('\"K2\" '\"V2\") '('\"Key1\" '\"Value1\")"));
  688. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("upsertObject"));
  689. }
  690. };
  691. TWordCountHive elementStat = { {TString("Write"), 0}, {TString("SECRET"), 0} };
  692. VerifyProgram(res, elementStat, verifyLine);
  693. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  694. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["SECRET"]);
  695. }
  696. Y_UNIT_TEST(CreateObjectWithFeaturesAndFlags) {
  697. NYql::TAstParseResult res = SqlToYql("USE plato; CREATE OBJECT secretId (TYPE SECRET) WITH (Key1=Value1, K2=V2, RECURSE);");
  698. UNIT_ASSERT(res.Root);
  699. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  700. if (word == "Write") {
  701. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("'('\"Key1\" '\"Value1\") '('\"RECURSE\")"));
  702. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("createObject"));
  703. }
  704. };
  705. TWordCountHive elementStat = { {TString("Write"), 0}, {TString("SECRET"), 0} };
  706. VerifyProgram(res, elementStat, verifyLine);
  707. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  708. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["SECRET"]);
  709. }
  710. Y_UNIT_TEST(Select1Type) {
  711. NYql::TAstParseResult res = SqlToYql("SELECT 1 type;");
  712. UNIT_ASSERT(res.Root);
  713. }
  714. Y_UNIT_TEST(SelectTableType) {
  715. NYql::TAstParseResult res = SqlToYql("USE plato; SELECT * from T type;");
  716. UNIT_ASSERT(res.Root);
  717. }
  718. Y_UNIT_TEST(CreateObjectNoFeatures) {
  719. NYql::TAstParseResult res = SqlToYql("USE plato; CREATE OBJECT secretId (TYPE SECRET);");
  720. UNIT_ASSERT(res.Root);
  721. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  722. if (word == "Write") {
  723. UNIT_ASSERT_VALUES_EQUAL(TString::npos, line.find("'features"));
  724. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("createObject"));
  725. }
  726. };
  727. TWordCountHive elementStat = { {TString("Write"), 0}, {TString("SECRET"), 0} };
  728. VerifyProgram(res, elementStat, verifyLine);
  729. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  730. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["SECRET"]);
  731. }
  732. Y_UNIT_TEST(AlterObjectWithFeatures) {
  733. NYql::TAstParseResult res = SqlToYql(
  734. "USE plato;\n"
  735. "declare $path as String;\n"
  736. "ALTER OBJECT secretId (TYPE SECRET) SET (Key1=$path, K2=V2);"
  737. );
  738. UNIT_ASSERT(res.Root);
  739. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  740. if (word == "Write") {
  741. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("'features"));
  742. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("'\"Key1\" (EvaluateAtom \"$path\""));
  743. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("'\"K2\" '\"V2\""));
  744. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("alterObject"));
  745. }
  746. };
  747. TWordCountHive elementStat = { {TString("Write"), 0}, {TString("SECRET"), 0} };
  748. VerifyProgram(res, elementStat, verifyLine);
  749. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  750. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["SECRET"]);
  751. }
  752. Y_UNIT_TEST(AlterObjectNoFeatures) {
  753. NYql::TAstParseResult res = SqlToYql("USE plato; ALTER OBJECT secretId (TYPE SECRET);");
  754. UNIT_ASSERT(!res.Root);
  755. }
  756. Y_UNIT_TEST(DropObjectNoFeatures) {
  757. NYql::TAstParseResult res = SqlToYql("USE plato; DROP OBJECT secretId (TYPE SECRET);");
  758. UNIT_ASSERT(res.Root);
  759. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  760. if (word == "Write") {
  761. UNIT_ASSERT_VALUES_EQUAL(TString::npos, line.find("'features"));
  762. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("dropObject"));
  763. }
  764. };
  765. TWordCountHive elementStat = { {TString("Write"), 0}, {TString("SECRET"), 0} };
  766. VerifyProgram(res, elementStat, verifyLine);
  767. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  768. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["SECRET"]);
  769. }
  770. Y_UNIT_TEST(DropObjectWithFeatures) {
  771. NYql::TAstParseResult res = SqlToYql("USE plato; DROP OBJECT secretId (TYPE SECRET) WITH (A, B, C);");
  772. UNIT_ASSERT(res.Root);
  773. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  774. if (word == "Write") {
  775. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("'features"));
  776. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("dropObject"));
  777. }
  778. };
  779. TWordCountHive elementStat = { {TString("Write"), 0}, {TString("SECRET"), 0} };
  780. VerifyProgram(res, elementStat, verifyLine);
  781. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  782. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["SECRET"]);
  783. }
  784. Y_UNIT_TEST(DropObjectWithOneOption) {
  785. NYql::TAstParseResult res = SqlToYql("USE plato; DROP OBJECT secretId (TYPE SECRET) WITH OVERRIDE;");
  786. UNIT_ASSERT(res.Root);
  787. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  788. if (word == "Write") {
  789. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("'features"));
  790. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("'\"OVERRIDE\""));
  791. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("dropObject"));
  792. }
  793. };
  794. TWordCountHive elementStat = { {TString("Write"), 0}, {TString("SECRET"), 0} };
  795. VerifyProgram(res, elementStat, verifyLine);
  796. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  797. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["SECRET"]);
  798. }
  799. Y_UNIT_TEST(DropObjectIfExists) {
  800. NYql::TAstParseResult res = SqlToYql("USE plato; DROP OBJECT IF EXISTS secretId (TYPE SECRET);");
  801. UNIT_ASSERT(res.Root);
  802. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  803. if (word == "Write") {
  804. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("dropObjectIfExists"));
  805. }
  806. };
  807. TWordCountHive elementStat = { {TString("Write"), 0}, {TString("SECRET"), 0} };
  808. VerifyProgram(res, elementStat, verifyLine);
  809. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  810. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["SECRET"]);
  811. }
  812. Y_UNIT_TEST(PrimaryKeyParseCorrect) {
  813. NYql::TAstParseResult res = SqlToYql("USE plato; CREATE TABLE tableName (Key Uint32, Subkey Int64, Value String, PRIMARY KEY (Key, Subkey));");
  814. UNIT_ASSERT(res.Root);
  815. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  816. if (word == "Write") {
  817. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("\"Key\""));
  818. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("\"Subkey\""));
  819. }
  820. };
  821. TWordCountHive elementStat = {{TString("Write"), 0}, {TString("primarykey"), 0}};
  822. VerifyProgram(res, elementStat, verifyLine);
  823. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  824. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["primarykey"]);
  825. }
  826. Y_UNIT_TEST(CreateTableNonNullableYqlTypeAstCorrect) {
  827. NYql::TAstParseResult res = SqlToYql("USE plato; CREATE TABLE t (a int32 not null);");
  828. UNIT_ASSERT(res.Root);
  829. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  830. if (word == "Write!") {
  831. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos,
  832. line.find(R"__((Write! world sink (Key '('tablescheme (String '"t"))) values '('('mode 'create) '('columns '('('"a" (DataType 'Int32) '('columnConstrains '('('not_null))) '())))))))__"));
  833. }
  834. };
  835. TWordCountHive elementStat = {{TString("Write!"), 0}};
  836. VerifyProgram(res, elementStat, verifyLine);
  837. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write!"]);
  838. }
  839. Y_UNIT_TEST(CreateTableNullableYqlTypeAstCorrect) {
  840. NYql::TAstParseResult res = SqlToYql("USE plato; CREATE TABLE t (a int32);");
  841. UNIT_ASSERT(res.Root);
  842. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  843. if (word == "Write!") {
  844. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos,
  845. line.find(R"__((Write! world sink (Key '('tablescheme (String '"t"))) values '('('mode 'create) '('columns '('('"a" (AsOptionalType (DataType 'Int32)) '('columnConstrains '()) '()))))))__"));
  846. }
  847. };
  848. TWordCountHive elementStat = {{TString("Write!"), 0}};
  849. VerifyProgram(res, elementStat, verifyLine);
  850. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write!"]);
  851. }
  852. Y_UNIT_TEST(CreateTableNonNullablePgTypeAstCorrect) {
  853. NYql::TAstParseResult res = SqlToYql("USE plato; CREATE TABLE t (a pg_int4 not null);");
  854. UNIT_ASSERT(res.Root);
  855. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  856. if (word == "Write!") {
  857. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos,
  858. line.find(R"__((Write! world sink (Key '('tablescheme (String '"t"))) values '('('mode 'create) '('columns '('('"a" (PgType '_int4) '('columnConstrains '('('not_null))) '())))))))__"));
  859. }
  860. };
  861. TWordCountHive elementStat = {{TString("Write!"), 0}};
  862. VerifyProgram(res, elementStat, verifyLine);
  863. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write!"]);
  864. }
  865. Y_UNIT_TEST(CreateTableNullablePgTypeAstCorrect) {
  866. NYql::TAstParseResult res = SqlToYql("USE plato; CREATE TABLE t (a pg_int4);");
  867. UNIT_ASSERT(res.Root);
  868. res.Root->PrettyPrintTo(Cout, PRETTY_FLAGS);
  869. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  870. if (word == "Write!") {
  871. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos,
  872. line.find(R"__((Write! world sink (Key '('tablescheme (String '"t"))) values '('('mode 'create) '('columns '('('"a" (AsOptionalType (PgType '_int4)) '('columnConstrains '()) '()))))))__"));
  873. }
  874. };
  875. TWordCountHive elementStat = {{TString("Write!"), 0}};
  876. VerifyProgram(res, elementStat, verifyLine);
  877. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write!"]);
  878. }
  879. Y_UNIT_TEST(CreateTableNullPkColumnsAreAllowed) {
  880. NYql::TAstParseResult res = SqlToYql("USE plato; CREATE TABLE t (a int32, primary key(a));");
  881. UNIT_ASSERT(res.Root);
  882. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  883. if (word == "Write!") {
  884. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos,
  885. line.find(R"__((Write! world sink (Key '('tablescheme (String '"t"))) values '('('mode 'create) '('columns '('('"a" (AsOptionalType (DataType 'Int32)) '('columnConstrains '()) '()))) '('primarykey '('"a")))))__"));
  886. }
  887. };
  888. TWordCountHive elementStat = {{TString("Write!"), 0}};
  889. VerifyProgram(res, elementStat, verifyLine);
  890. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write!"]);
  891. }
  892. Y_UNIT_TEST(CreateTableNotNullPkColumnsAreIdempotentAstCorrect) {
  893. NYql::TAstParseResult res = SqlToYql("USE plato; CREATE TABLE t (a int32 not null, primary key(a));");
  894. UNIT_ASSERT(res.Root);
  895. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  896. if (word == "Write!") {
  897. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos,
  898. line.find(R"__((Write! world sink (Key '('tablescheme (String '"t"))) values '('('mode 'create) '('columns '('('"a" (DataType 'Int32) '('columnConstrains '('('not_null))) '()))) '('primarykey '('"a"))))))__"));
  899. }
  900. };
  901. TWordCountHive elementStat = {{TString("Write!"), 0}};
  902. VerifyProgram(res, elementStat, verifyLine);
  903. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write!"]);
  904. }
  905. Y_UNIT_TEST(CreateTableWithIfNotExists) {
  906. NYql::TAstParseResult res = SqlToYql("USE plato; CREATE TABLE IF NOT EXISTS t (a int32, primary key(a));");
  907. UNIT_ASSERT(res.Root);
  908. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  909. if (word == "Write!") {
  910. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos,
  911. line.find(R"__((Write! world sink (Key '('tablescheme (String '"t"))) values '('('mode 'create_if_not_exists) '('columns '('('"a" (AsOptionalType (DataType 'Int32)) '('columnConstrains '()) '()))) '('primarykey '('"a")))))__"));
  912. }
  913. };
  914. TWordCountHive elementStat = {{TString("Write!"), 0}};
  915. VerifyProgram(res, elementStat, verifyLine);
  916. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write!"]);
  917. }
  918. Y_UNIT_TEST(CreateTempTable) {
  919. NYql::TAstParseResult res = SqlToYql("USE plato; CREATE TEMP TABLE t (a int32, primary key(a));");
  920. UNIT_ASSERT(res.Root);
  921. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  922. if (word == "Write!") {
  923. UNIT_ASSERT_VALUES_UNEQUAL_C(TString::npos,
  924. line.find(R"__((Write! world sink (Key '('tablescheme (String '"t"))) values '('('mode 'create) '('columns '('('"a" (AsOptionalType (DataType 'Int32)) '('columnConstrains '()) '()))) '('primarykey '('"a")) '('temporary))))__"), line);
  925. }
  926. };
  927. TWordCountHive elementStat = {{TString("Write!"), 0}};
  928. VerifyProgram(res, elementStat, verifyLine);
  929. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write!"]);
  930. }
  931. Y_UNIT_TEST(CreateTemporaryTable) {
  932. NYql::TAstParseResult res = SqlToYql("USE plato; CREATE TEMPORARY TABLE t (a int32, primary key(a));");
  933. UNIT_ASSERT(res.Root);
  934. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  935. if (word == "Write!") {
  936. UNIT_ASSERT_VALUES_UNEQUAL_C(TString::npos,
  937. line.find(R"__((Write! world sink (Key '('tablescheme (String '"t"))) values '('('mode 'create) '('columns '('('"a" (AsOptionalType (DataType 'Int32)) '('columnConstrains '()) '()))) '('primarykey '('"a")) '('temporary))))__"), line);
  938. }
  939. };
  940. TWordCountHive elementStat = {{TString("Write!"), 0}};
  941. VerifyProgram(res, elementStat, verifyLine);
  942. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write!"]);
  943. }
  944. Y_UNIT_TEST(CreateTableWithoutTypes) {
  945. NYql::TAstParseResult res = SqlToYql("USE plato; CREATE TABLE t (a, primary key(a));");
  946. UNIT_ASSERT(!res.Root);
  947. }
  948. Y_UNIT_TEST(CreateTableAsSelectWithTypes) {
  949. NYql::TAstParseResult res = SqlToYql("USE plato; CREATE TABLE t (a int32, primary key(a)) AS SELECT * FROM ts;");
  950. UNIT_ASSERT(!res.Root);
  951. }
  952. Y_UNIT_TEST(CreateTableAsSelect) {
  953. NYql::TAstParseResult res = SqlToYql("USE plato; CREATE TABLE t (a, b, primary key(a)) AS SELECT * FROM ts;");
  954. UNIT_ASSERT_C(res.Root, res.Issues.ToString());
  955. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  956. if (word == "Write!") {
  957. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos,
  958. line.find(R"__((let world (Write! world sink (Key '('tablescheme (String '"t"))) values '('('mode 'create) '('columns '('('"a") '('"b"))) '('primarykey '('"a"))))))__"));
  959. }
  960. if (word == "Read!") {
  961. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos,
  962. line.find(R"__((Read! world (DataSource '"yt" '"plato") (MrTableConcat (Key '('table (String '"ts")))))__"));
  963. }
  964. };
  965. TWordCountHive elementStat = {{TString("Write!"), 0}, {TString("Read!"), 0}};
  966. VerifyProgram(res, elementStat, verifyLine);
  967. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write!"]);
  968. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Read!"]);
  969. }
  970. Y_UNIT_TEST(CreateTableAsSelectOnlyPrimary) {
  971. NYql::TAstParseResult res = SqlToYql("USE plato; CREATE TABLE t (primary key(a)) AS SELECT * FROM ts;");
  972. UNIT_ASSERT_C(res.Root, res.Issues.ToString());
  973. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  974. if (word == "Write!") {
  975. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos,
  976. line.find(R"__((let world (Write! world sink (Key '('tablescheme (String '"t"))) values '('('mode 'create) '('columns '()) '('primarykey '('"a"))))))__"));
  977. }
  978. if (word == "Read!") {
  979. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos,
  980. line.find(R"__((Read! world (DataSource '"yt" '"plato") (MrTableConcat (Key '('table (String '"ts")))))__"));
  981. }
  982. };
  983. TWordCountHive elementStat = {{TString("Write!"), 0}, {TString("Read!"), 0}};
  984. VerifyProgram(res, elementStat, verifyLine);
  985. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write!"]);
  986. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Read!"]);
  987. }
  988. Y_UNIT_TEST(CreateTableAsValuesFail) {
  989. NYql::TAstParseResult res = SqlToYql("USE plato; CREATE TABLE t (a, primary key(a)) AS VALUES (1), (2);");
  990. UNIT_ASSERT(!res.Root);
  991. }
  992. Y_UNIT_TEST(CreateTableDuplicatedPkColumnsFail) {
  993. NYql::TAstParseResult res = SqlToYql("USE plato; CREATE TABLE t (a int32 not null, primary key(a, a));");
  994. UNIT_ASSERT(!res.Root);
  995. }
  996. Y_UNIT_TEST(DeleteFromTableByKey) {
  997. NYql::TAstParseResult res = SqlToYql("delete from plato.Input where key = 200;", 10, "kikimr");
  998. UNIT_ASSERT(res.Root);
  999. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  1000. if (word == "Write") {
  1001. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("('mode 'delete)"));
  1002. }
  1003. };
  1004. TWordCountHive elementStat = {{TString("Write"), 0}};
  1005. VerifyProgram(res, elementStat, verifyLine);
  1006. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  1007. }
  1008. Y_UNIT_TEST(DeleteFromTable) {
  1009. NYql::TAstParseResult res = SqlToYql("delete from plato.Input;", 10, "kikimr");
  1010. UNIT_ASSERT(res.Root);
  1011. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  1012. if (word == "Write") {
  1013. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("('mode 'delete)"));
  1014. }
  1015. };
  1016. TWordCountHive elementStat = {{TString("Write"), 0}};
  1017. VerifyProgram(res, elementStat, verifyLine);
  1018. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  1019. }
  1020. Y_UNIT_TEST(DeleteFromTableOnValues) {
  1021. NYql::TAstParseResult res = SqlToYql("delete from plato.Input on (key) values (1);",
  1022. 10, "kikimr");
  1023. UNIT_ASSERT(res.Root);
  1024. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  1025. if (word == "Write") {
  1026. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("('mode 'delete_on)"));
  1027. }
  1028. };
  1029. TWordCountHive elementStat = {{TString("Write"), 0}};
  1030. VerifyProgram(res, elementStat, verifyLine);
  1031. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  1032. }
  1033. Y_UNIT_TEST(DeleteFromTableOnSelect) {
  1034. NYql::TAstParseResult res = SqlToYql(
  1035. "delete from plato.Input on select key from plato.Input where value > 0;", 10, "kikimr");
  1036. UNIT_ASSERT(res.Root);
  1037. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  1038. if (word == "Write") {
  1039. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("('mode 'delete_on)"));
  1040. }
  1041. };
  1042. TWordCountHive elementStat = {{TString("Write"), 0}};
  1043. VerifyProgram(res, elementStat, verifyLine);
  1044. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  1045. }
  1046. Y_UNIT_TEST(UpdateByValues) {
  1047. NYql::TAstParseResult res = SqlToYql("update plato.Input set key = 777, value = 'cool' where key = 200;", 10, "kikimr");
  1048. UNIT_ASSERT(res.Root);
  1049. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  1050. if (word == "Write") {
  1051. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("('mode 'update)"));
  1052. } else if (word == "AsStruct") {
  1053. const bool isKey = line.find("key") != TString::npos;
  1054. const bool isValue = line.find("value") != TString::npos;
  1055. UNIT_ASSERT(isKey || isValue);
  1056. if (isKey) {
  1057. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(Quote("777")));
  1058. } else if (isValue) {
  1059. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(Quote("cool")));
  1060. }
  1061. }
  1062. };
  1063. TWordCountHive elementStat = {{TString("Write"), 0}, {TString("AsStruct"), 0}};
  1064. VerifyProgram(res, elementStat, verifyLine);
  1065. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  1066. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["AsStruct"]);
  1067. }
  1068. Y_UNIT_TEST(UpdateByMultiValues) {
  1069. NYql::TAstParseResult res = SqlToYql("update plato.Input set (key, value, subkey) = ('2','ddd',':') where key = 200;", 10, "kikimr");
  1070. UNIT_ASSERT(res.Root);
  1071. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  1072. if (word == "Write") {
  1073. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("('mode 'update)"));
  1074. } else if (word == "AsStruct") {
  1075. const bool isKey = line.find("key") != TString::npos;
  1076. const bool isSubkey = line.find("subkey") != TString::npos;
  1077. const bool isValue = line.find("value") != TString::npos;
  1078. UNIT_ASSERT(isKey || isSubkey || isValue);
  1079. if (isKey && !isSubkey) {
  1080. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(Quote("2")));
  1081. } else if (isSubkey) {
  1082. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(Quote(":")));
  1083. } else if (isValue) {
  1084. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(Quote("ddd")));
  1085. }
  1086. }
  1087. };
  1088. TWordCountHive elementStat = {{TString("Write"), 0}, {TString("AsStruct"), 0}};
  1089. VerifyProgram(res, elementStat, verifyLine);
  1090. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  1091. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["AsStruct"]);
  1092. }
  1093. Y_UNIT_TEST(UpdateBySelect) {
  1094. NYql::TAstParseResult res = SqlToYql("update plato.Input set (key, value, subkey) = (select key, value, subkey from plato.Input where key = 911) where key = 200;", 10, "kikimr");
  1095. UNIT_ASSERT(res.Root);
  1096. int lineIndex = 0;
  1097. int writeLineIndex = -1;
  1098. bool found = false;
  1099. TVerifyLineFunc verifyLine = [&lineIndex, &writeLineIndex, &found](const TString& word, const TString& line) {
  1100. if (word == "Write") {
  1101. writeLineIndex = lineIndex;
  1102. found = line.find("('mode 'update)") != TString::npos;
  1103. } else if (word == "mode") {
  1104. found |= lineIndex == writeLineIndex + 1 && line.find("('mode 'update)") != TString::npos;
  1105. UNIT_ASSERT(found);
  1106. }
  1107. ++lineIndex;
  1108. };
  1109. TWordCountHive elementStat = {{TString("Write"), 0}, {TString("mode"), 0}};
  1110. VerifyProgram(res, elementStat, verifyLine);
  1111. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  1112. }
  1113. Y_UNIT_TEST(UpdateSelfModifyAll) {
  1114. NYql::TAstParseResult res = SqlToYql("update plato.Input set subkey = subkey + 's';", 10, "kikimr");
  1115. UNIT_ASSERT(res.Root);
  1116. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  1117. if (word == "Write") {
  1118. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("('mode 'update)"));
  1119. } else if (word == "AsStruct") {
  1120. const bool isSubkey = line.find("subkey") != TString::npos;
  1121. UNIT_ASSERT(isSubkey);
  1122. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(Quote("subkey")));
  1123. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(Quote("s")));
  1124. }
  1125. };
  1126. TWordCountHive elementStat = {{TString("Write"), 0}, {TString("AsStruct"), 0}};
  1127. VerifyProgram(res, elementStat, verifyLine);
  1128. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  1129. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["AsStruct"]);
  1130. }
  1131. Y_UNIT_TEST(UpdateOnValues) {
  1132. NYql::TAstParseResult res = SqlToYql("update plato.Input on (key, value) values (5, 'cool')", 10, "kikimr");
  1133. UNIT_ASSERT(res.Root);
  1134. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  1135. if (word == "Write") {
  1136. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("('mode 'update_on)"));
  1137. }
  1138. };
  1139. TWordCountHive elementStat = {{TString("Write"), 0}};
  1140. VerifyProgram(res, elementStat, verifyLine);
  1141. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  1142. }
  1143. Y_UNIT_TEST(UpdateOnSelect) {
  1144. NYql::TAstParseResult res = SqlToYql(
  1145. "update plato.Input on select key, value + 1 as value from plato.Input", 10, "kikimr");
  1146. UNIT_ASSERT(res.Root);
  1147. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  1148. if (word == "Write") {
  1149. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("('mode 'update_on)"));
  1150. }
  1151. };
  1152. TWordCountHive elementStat = {{TString("Write"), 0}};
  1153. VerifyProgram(res, elementStat, verifyLine);
  1154. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  1155. }
  1156. Y_UNIT_TEST(UnionAllTest) {
  1157. NYql::TAstParseResult res = SqlToYql("SELECT key FROM plato.Input UNION ALL select subkey FROM plato.Input;");
  1158. UNIT_ASSERT(res.Root);
  1159. TWordCountHive elementStat = {{TString("UnionAll"), 0}};
  1160. VerifyProgram(res, elementStat, {});
  1161. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["UnionAll"]);
  1162. }
  1163. Y_UNIT_TEST(UnionTest) {
  1164. NYql::TAstParseResult res = SqlToYql("SELECT key FROM plato.Input UNION select subkey FROM plato.Input;");
  1165. UNIT_ASSERT(res.Root);
  1166. TWordCountHive elementStat = {{TString("Union"), 0}};
  1167. VerifyProgram(res, elementStat, {});
  1168. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Union"]);
  1169. }
  1170. Y_UNIT_TEST(UnionAggregationTest) {
  1171. NYql::TAstParseResult res = SqlToYql(R"(
  1172. SELECT 1
  1173. UNION ALL
  1174. SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
  1175. UNION
  1176. SELECT 1 UNION SELECT 1 UNION SELECT 1 UNION SELECT 1
  1177. UNION ALL
  1178. SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1;
  1179. )");
  1180. UNIT_ASSERT(res.Root);
  1181. TWordCountHive elementStat = {{TString("Union"), 0}, {TString("UnionAll"), 0}};
  1182. VerifyProgram(res, elementStat, {});
  1183. UNIT_ASSERT_VALUES_EQUAL(2, elementStat["UnionAll"]);
  1184. UNIT_ASSERT_VALUES_EQUAL(3, elementStat["Union"]);
  1185. }
  1186. Y_UNIT_TEST(DeclareDecimalParameter) {
  1187. NYql::TAstParseResult res = SqlToYql("declare $value as Decimal(22,9); select $value as cnt;");
  1188. UNIT_ASSERT(res.Root);
  1189. }
  1190. Y_UNIT_TEST(SimpleGroupBy) {
  1191. NYql::TAstParseResult res = SqlToYql("select count(1),z from plato.Input group by key as z order by z;");
  1192. UNIT_ASSERT(res.Root);
  1193. }
  1194. Y_UNIT_TEST(EmptyColumnName0) {
  1195. /// Now it's parsed well and error occur on validate step like "4:31:Empty struct member name is not allowed" in "4:31:Function: AddMember"
  1196. NYql::TAstParseResult res = SqlToYql("insert into plato.Output (``, list1) values (0, AsList(0, 1, 2));");
  1197. /// Verify that parsed well without crash
  1198. UNIT_ASSERT(res.Root);
  1199. }
  1200. Y_UNIT_TEST(KikimrRollback) {
  1201. NYql::TAstParseResult res = SqlToYql("use plato; select * from Input; rollback;", 10, "kikimr");
  1202. UNIT_ASSERT(res.Root);
  1203. TWordCountHive elementStat = {{TString("rollback"), 0}};
  1204. VerifyProgram(res, elementStat);
  1205. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["rollback"]);
  1206. }
  1207. Y_UNIT_TEST(PragmaFile) {
  1208. NYql::TAstParseResult res = SqlToYql(R"(pragma file("HW", "sbr:181041334");)");
  1209. UNIT_ASSERT(res.Root);
  1210. TWordCountHive elementStat = {{TString(R"((let world (Configure! world (DataSource '"config") '"AddFileByUrl" '"HW" '"sbr:181041334")))"), 0}};
  1211. VerifyProgram(res, elementStat);
  1212. UNIT_ASSERT_VALUES_EQUAL(1, elementStat.cbegin()->second);
  1213. }
  1214. Y_UNIT_TEST(DoNotCrashOnNamedInFilter) {
  1215. NYql::TAstParseResult res = SqlToYql("USE plato; $all = ($table_name) -> { return true; }; SELECT * FROM FILTER(Input, $all)");
  1216. UNIT_ASSERT(res.Root);
  1217. }
  1218. Y_UNIT_TEST(PragmasFileAndUdfOrder) {
  1219. NYql::TAstParseResult res = SqlToYql(R"(
  1220. PRAGMA file("libvideoplayers_udf.so", "https://proxy.sandbox.yandex-team.ru/235185290");
  1221. PRAGMA udf("libvideoplayers_udf.so");
  1222. )");
  1223. UNIT_ASSERT(res.Root);
  1224. const auto programm = GetPrettyPrint(res);
  1225. const auto file = programm.find("AddFileByUrl");
  1226. const auto udfs = programm.find("ImportUdfs");
  1227. UNIT_ASSERT(file < udfs);
  1228. }
  1229. Y_UNIT_TEST(ProcessUserType) {
  1230. NYql::TAstParseResult res = SqlToYql("process plato.Input using Kikimr::PushData(TableRows());", 1, TString(NYql::KikimrProviderName));
  1231. UNIT_ASSERT(res.Root);
  1232. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  1233. if (word == "Kikimr.PushData") {
  1234. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("TupleType"));
  1235. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("TypeOf"));
  1236. }
  1237. };
  1238. TWordCountHive elementStat = {{TString("Kikimr.PushData"), 0}};
  1239. VerifyProgram(res, elementStat, verifyLine);
  1240. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Kikimr.PushData"]);
  1241. }
  1242. Y_UNIT_TEST(ProcessUserTypeAuth) {
  1243. NYql::TAstParseResult res = SqlToYql("process plato.Input using YDB::PushData(TableRows(), AsTuple('oauth', SecureParam('api:oauth')));", 1, TString(NYql::KikimrProviderName));
  1244. UNIT_ASSERT(res.Root);
  1245. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  1246. if (word == "YDB.PushData") {
  1247. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("TupleType"));
  1248. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("TypeOf"));
  1249. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("api:oauth"));
  1250. }
  1251. };
  1252. TWordCountHive elementStat = {{TString("YDB.PushData"), 0}};
  1253. VerifyProgram(res, elementStat, verifyLine);
  1254. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["YDB.PushData"]);
  1255. }
  1256. Y_UNIT_TEST(SelectStreamRtmr) {
  1257. NYql::TAstParseResult res = SqlToYql(
  1258. "USE plato; INSERT INTO Output SELECT STREAM key FROM Input;",
  1259. 10, TString(NYql::RtmrProviderName));
  1260. UNIT_ASSERT(res.Root);
  1261. res = SqlToYql(
  1262. "USE plato; INSERT INTO Output SELECT key FROM Input;",
  1263. 10, TString(NYql::RtmrProviderName));
  1264. UNIT_ASSERT(res.Root);
  1265. }
  1266. Y_UNIT_TEST(SelectStreamRtmrJoinWithYt) {
  1267. NYql::TAstParseResult res = SqlToYql(
  1268. "USE plato; INSERT INTO Output SELECT STREAM key FROM Input LEFT JOIN hahn.ttt as t ON Input.key = t.Name;",
  1269. 10, TString(NYql::RtmrProviderName));
  1270. UNIT_ASSERT(res.Root);
  1271. }
  1272. Y_UNIT_TEST(SelectStreamNonRtmr) {
  1273. NYql::TAstParseResult res = SqlToYql(
  1274. "USE plato; INSERT INTO Output SELECT STREAM key FROM Input;",
  1275. 10);
  1276. UNIT_ASSERT(!res.Root);
  1277. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:31: Error: SELECT STREAM is unsupported for non-streaming sources\n");
  1278. }
  1279. Y_UNIT_TEST(GroupByHopRtmr) {
  1280. NYql::TAstParseResult res = SqlToYql(R"(
  1281. USE plato; INSERT INTO Output SELECT key, SUM(value) AS value FROM Input
  1282. GROUP BY key, HOP(subkey, "PT10S", "PT30S", "PT20S");
  1283. )", 10, TString(NYql::RtmrProviderName));
  1284. UNIT_ASSERT(res.Root);
  1285. }
  1286. Y_UNIT_TEST(GroupByHopRtmrSubquery) {
  1287. // 'use plato' intentially avoided
  1288. NYql::TAstParseResult res = SqlToYql(R"(
  1289. SELECT COUNT(*) AS value FROM (SELECT * FROM plato.Input)
  1290. GROUP BY HOP(Data, "PT10S", "PT30S", "PT20S")
  1291. )", 10, TString(NYql::RtmrProviderName));
  1292. UNIT_ASSERT(res.Root);
  1293. }
  1294. Y_UNIT_TEST(GroupByHopRtmrSubqueryBinding) {
  1295. NYql::TAstParseResult res = SqlToYql(R"(
  1296. USE plato;
  1297. $q = SELECT * FROM Input;
  1298. INSERT INTO Output SELECT STREAM * FROM (
  1299. SELECT COUNT(*) AS value FROM $q
  1300. GROUP BY HOP(Data, "PT10S", "PT30S", "PT20S")
  1301. );
  1302. )", 10, TString(NYql::RtmrProviderName));
  1303. UNIT_ASSERT(res.Root);
  1304. }
  1305. Y_UNIT_TEST(GroupByNoHopRtmr) {
  1306. NYql::TAstParseResult res = SqlToYql(R"(
  1307. USE plato; INSERT INTO Output SELECT STREAM key, SUM(value) AS value FROM Input
  1308. GROUP BY key;
  1309. )", 10, TString(NYql::RtmrProviderName));
  1310. UNIT_ASSERT(!res.Root);
  1311. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:3:22: Error: Streaming group by query must have a hopping window specification.\n");
  1312. }
  1313. Y_UNIT_TEST(KikimrInserts) {
  1314. NYql::TAstParseResult res = SqlToYql(R"(
  1315. USE plato;
  1316. INSERT INTO Output SELECT key, value FROM Input;
  1317. INSERT OR ABORT INTO Output SELECT key, value FROM Input;
  1318. INSERT OR IGNORE INTO Output SELECT key, value FROM Input;
  1319. INSERT OR REVERT INTO Output SELECT key, value FROM Input;
  1320. )", 10, TString(NYql::KikimrProviderName));
  1321. UNIT_ASSERT(res.Root);
  1322. }
  1323. Y_UNIT_TEST(WarnMissingIsBeforeNotNull) {
  1324. NYql::TAstParseResult res = SqlToYql("select 1 NOT NULL");
  1325. UNIT_ASSERT(res.Root);
  1326. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:8: Warning: Missing IS keyword before NOT NULL, code: 4507\n");
  1327. }
  1328. Y_UNIT_TEST(Subqueries) {
  1329. NYql::TAstParseResult res = SqlToYql(R"(
  1330. USE plato;
  1331. $sq1 = (SELECT * FROM plato.Input);
  1332. $sq2 = SELECT * FROM plato.Input;
  1333. $squ1 = (
  1334. SELECT * FROM plato.Input
  1335. UNION ALL
  1336. SELECT * FROM plato.Input
  1337. );
  1338. $squ2 =
  1339. SELECT * FROM plato.Input
  1340. UNION ALL
  1341. SELECT * FROM plato.Input;
  1342. $squ3 = (
  1343. (SELECT * FROM plato.Input)
  1344. UNION ALL
  1345. (SELECT * FROM plato.Input)
  1346. );
  1347. SELECT * FROM $sq1;
  1348. SELECT * FROM $sq2;
  1349. SELECT * FROM $squ1;
  1350. SELECT * FROM $squ2;
  1351. SELECT * FROM $squ3;
  1352. )");
  1353. UNIT_ASSERT(res.Root);
  1354. }
  1355. Y_UNIT_TEST(SubqueriesJoin) {
  1356. NYql::TAstParseResult res = SqlToYql(R"(
  1357. USE plato;
  1358. $left = SELECT * FROM plato.Input1 WHERE value != "BadValue";
  1359. $right = SELECT * FROM plato.Input2;
  1360. SELECT * FROM $left AS l
  1361. JOIN $right AS r
  1362. ON l.key == r.key;
  1363. )");
  1364. UNIT_ASSERT(res.Root);
  1365. }
  1366. Y_UNIT_TEST(AnyInBackticksAsTableName) {
  1367. NYql::TAstParseResult res = SqlToYql("use plato; select * from `any`;");
  1368. UNIT_ASSERT(res.Root);
  1369. }
  1370. Y_UNIT_TEST(AnyJoinForTableAndSubQuery) {
  1371. NYql::TAstParseResult res = SqlToYql(R"(
  1372. USE plato;
  1373. $r = SELECT * FROM plato.Input2;
  1374. SELECT * FROM ANY plato.Input1 AS l
  1375. LEFT JOIN ANY $r AS r
  1376. USING (key);
  1377. )");
  1378. UNIT_ASSERT(res.Root);
  1379. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  1380. if (word == "EquiJoin") {
  1381. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("'('left 'any)"));
  1382. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("'('right 'any)"));
  1383. }
  1384. };
  1385. TWordCountHive elementStat = {{TString("left"), 0}, {TString("right"), 0}};
  1386. VerifyProgram(res, elementStat, verifyLine);
  1387. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["left"]);
  1388. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["right"]);
  1389. }
  1390. Y_UNIT_TEST(AnyJoinForTableAndTableSource) {
  1391. NYql::TAstParseResult res = SqlToYql(R"(
  1392. USE plato;
  1393. $r = AsList(
  1394. AsStruct("aaa" as key, "bbb" as subkey, "ccc" as value)
  1395. );
  1396. SELECT * FROM ANY plato.Input1 AS l
  1397. LEFT JOIN ANY AS_TABLE($r) AS r
  1398. USING (key);
  1399. )");
  1400. UNIT_ASSERT(res.Root);
  1401. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  1402. if (word == "EquiJoin") {
  1403. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("'('left 'any)"));
  1404. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("'('right 'any)"));
  1405. }
  1406. };
  1407. TWordCountHive elementStat = {{TString("left"), 0}, {TString("right"), 0}};
  1408. VerifyProgram(res, elementStat, verifyLine);
  1409. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["left"]);
  1410. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["right"]);
  1411. }
  1412. Y_UNIT_TEST(AnyJoinNested) {
  1413. NYql::TAstParseResult res = SqlToYql(R"(
  1414. USE plato;
  1415. FROM ANY Input1 as a
  1416. JOIN Input2 as b ON a.key = b.key
  1417. LEFT JOIN ANY Input3 as c ON a.key = c.key
  1418. RIGHT JOIN ANY Input4 as d ON d.key = b.key
  1419. CROSS JOIN Input5
  1420. SELECT *;
  1421. )");
  1422. UNIT_ASSERT(res.Root);
  1423. TWordCountHive elementStat = {{TString("left"), 0}, {TString("right"), 0}};
  1424. VerifyProgram(res, elementStat);
  1425. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["left"]);
  1426. UNIT_ASSERT_VALUES_EQUAL(2, elementStat["right"]);
  1427. }
  1428. Y_UNIT_TEST(InlineAction) {
  1429. NYql::TAstParseResult res = SqlToYql(
  1430. "do begin\n"
  1431. " select 1\n"
  1432. "; end do\n");
  1433. UNIT_ASSERT(res.Root);
  1434. UNIT_ASSERT_NO_DIFF(Err2Str(res), "");
  1435. }
  1436. Y_UNIT_TEST(FlattenByCorrelationName) {
  1437. UNIT_ASSERT(SqlToYql("select * from plato.Input as t flatten by t.x").IsOk());
  1438. UNIT_ASSERT(SqlToYql("select * from plato.Input as t flatten by t -- same as flatten by t.t").IsOk());
  1439. }
  1440. Y_UNIT_TEST(DiscoveryMode) {
  1441. UNIT_ASSERT(SqlToYqlWithMode("insert into plato.Output select * from plato.Input", NSQLTranslation::ESqlMode::DISCOVERY).IsOk());
  1442. UNIT_ASSERT(SqlToYqlWithMode("select * from plato.concat(Input1, Input2)", NSQLTranslation::ESqlMode::DISCOVERY).IsOk());
  1443. UNIT_ASSERT(SqlToYqlWithMode("select * from plato.each(AsList(\"Input1\", \"Input2\"))", NSQLTranslation::ESqlMode::DISCOVERY).IsOk());
  1444. }
  1445. Y_UNIT_TEST(CubeWithAutoGeneratedLikeColumnName) {
  1446. UNIT_ASSERT(SqlToYql("select key,subkey,group from plato.Input group by cube(key,subkey,group)").IsOk());
  1447. }
  1448. Y_UNIT_TEST(CubeWithAutoGeneratedLikeAlias) {
  1449. UNIT_ASSERT(SqlToYql("select key,subkey,group from plato.Input group by cube(key,subkey,value as group)").IsOk());
  1450. }
  1451. Y_UNIT_TEST(FilterCanBeUsedAsColumnIdOrBind) {
  1452. UNIT_ASSERT(SqlToYql("select filter from plato.Input").IsOk());
  1453. UNIT_ASSERT(SqlToYql("select 1 as filter").IsOk());
  1454. UNIT_ASSERT(SqlToYql("$filter = 1; select $filter").IsOk());
  1455. }
  1456. Y_UNIT_TEST(DuplicateSemicolonsAreAllowedBetweenTopLevelStatements) {
  1457. UNIT_ASSERT(SqlToYql(";;select 1; ; select 2;/*comment*/;select 3;;--comment\n;select 4;;").IsOk());
  1458. }
  1459. Y_UNIT_TEST(DuplicateAndMissingTrailingSemicolonsAreAllowedBetweenActionStatements) {
  1460. TString req =
  1461. "define action $action($b,$c) as\n"
  1462. " ;;$d = $b + $c;\n"
  1463. " select $b;\n"
  1464. " select $c;;\n"
  1465. " select $d,\n"
  1466. "end define;\n"
  1467. "\n"
  1468. "do $action(1,2);";
  1469. UNIT_ASSERT(SqlToYql(req).IsOk());
  1470. }
  1471. Y_UNIT_TEST(DuplicateAndMissingTrailingSemicolonsAreAllowedBetweenInlineActionStatements) {
  1472. TString req =
  1473. "do begin\n"
  1474. " ;select 1,\n"
  1475. "end do;\n"
  1476. "evaluate for $i in AsList(1,2,3) do begin\n"
  1477. " select $i;;\n"
  1478. " select $i + $i;;\n"
  1479. "end do;";
  1480. UNIT_ASSERT(SqlToYql(req).IsOk());
  1481. }
  1482. Y_UNIT_TEST(DuplicateSemicolonsAreAllowedBetweenLambdaStatements) {
  1483. TString req =
  1484. "$x=1;\n"
  1485. "$foo = ($a, $b)->{\n"
  1486. " ;;$v = $a + $b;\n"
  1487. " $bar = ($c) -> {; return $c << $x};;\n"
  1488. " return $bar($v);;\n"
  1489. "};\n"
  1490. "select $foo(1,2);";
  1491. UNIT_ASSERT(SqlToYql(req).IsOk());
  1492. }
  1493. Y_UNIT_TEST(StringLiteralWithEscapedBackslash) {
  1494. NYql::TAstParseResult res1 = SqlToYql(R"foo(SELECT 'a\\';)foo");
  1495. NYql::TAstParseResult res2 = SqlToYql(R"foo(SELECT "a\\";)foo");
  1496. UNIT_ASSERT(res1.Root);
  1497. UNIT_ASSERT(res2.Root);
  1498. TWordCountHive elementStat = {{TString("a\\"), 0}};
  1499. VerifyProgram(res1, elementStat);
  1500. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["a\\"]);
  1501. VerifyProgram(res2, elementStat);
  1502. UNIT_ASSERT_VALUES_EQUAL(2, elementStat["a\\"]);
  1503. }
  1504. Y_UNIT_TEST(StringMultiLineLiteralWithEscapes) {
  1505. UNIT_ASSERT(SqlToYql("SELECT @@@foo@@@@bar@@@").IsOk());
  1506. UNIT_ASSERT(SqlToYql("SELECT @@@@@@@@@").IsOk());
  1507. }
  1508. Y_UNIT_TEST(StringMultiLineLiteralConsequitiveAt) {
  1509. UNIT_ASSERT(!SqlToYql("SELECT @").IsOk());
  1510. UNIT_ASSERT(!SqlToYql("SELECT @@").IsOk());
  1511. UNIT_ASSERT(!SqlToYql("SELECT @@@").IsOk());
  1512. UNIT_ASSERT( SqlToYql("SELECT @@@@").IsOk());
  1513. UNIT_ASSERT( SqlToYql("SELECT @@@@@").IsOk());
  1514. UNIT_ASSERT(!SqlToYql("SELECT @@@@@@").IsOk());
  1515. UNIT_ASSERT(!SqlToYql("SELECT @@@@@@@").IsOk());
  1516. UNIT_ASSERT( SqlToYql("SELECT @@@@@@@@").IsOk());
  1517. UNIT_ASSERT( SqlToYql("SELECT @@@@@@@@@").IsOk());
  1518. UNIT_ASSERT(!SqlToYql("SELECT @@@@@@@@@@").IsOk());
  1519. }
  1520. Y_UNIT_TEST(ConstnessForListDictSetCreate) {
  1521. auto req = "$foo = ($x, $y) -> (\"aaaa\");\n"
  1522. "\n"
  1523. "select\n"
  1524. " $foo(sum(key), ListCreate(String)),\n"
  1525. " $foo(sum(key), DictCreate(String, String)),\n"
  1526. " $foo(sum(key), SetCreate(String)),\n"
  1527. "from (select 1 as key);";
  1528. UNIT_ASSERT(SqlToYql(req).IsOk());
  1529. }
  1530. Y_UNIT_TEST(CanUseEmptyTupleInWindowPartitionBy) {
  1531. auto req = "select sum(key) over w\n"
  1532. "from plato.Input\n"
  1533. "window w as (partition compact by (), (subkey), (), value || value as dvalue);";
  1534. UNIT_ASSERT(SqlToYql(req).IsOk());
  1535. }
  1536. Y_UNIT_TEST(DenyAnsiOrderByLimitLegacyMode) {
  1537. auto req = "pragma DisableAnsiOrderByLimitInUnionAll;\n"
  1538. "use plato;\n"
  1539. "\n"
  1540. "select * from Input order by key limit 10\n"
  1541. "union all\n"
  1542. "select * from Input order by key limit 1;";
  1543. auto res = SqlToYql(req);
  1544. UNIT_ASSERT(!res.Root);
  1545. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:8: Error: DisableAnsiOrderByLimitInUnionAll pragma is deprecated and no longer supported\n");
  1546. }
  1547. Y_UNIT_TEST(ReduceUsingUdfWithShortcutsWorks) {
  1548. auto req = "use plato;\n"
  1549. "\n"
  1550. "$arg = 'foo';\n"
  1551. "$func = XXX::YYY($arg);\n"
  1552. "\n"
  1553. "REDUCE Input ON key using $func(subkey);\n"
  1554. "REDUCE Input ON key using $func(UUU::VVV(TableRow()));\n";
  1555. UNIT_ASSERT(SqlToYql(req).IsOk());
  1556. req = "use plato;\n"
  1557. "\n"
  1558. "$arg = 'foo';\n"
  1559. "$func = XXX::YYY($arg);\n"
  1560. "\n"
  1561. "REDUCE Input ON key using all $func(subkey);\n"
  1562. "REDUCE Input ON key using all $func(UUU::VVV(TableRow()));";
  1563. UNIT_ASSERT(SqlToYql(req).IsOk());
  1564. }
  1565. Y_UNIT_TEST(YsonDisableStrict) {
  1566. UNIT_ASSERT(SqlToYql("pragma yson.DisableStrict = \"false\";").IsOk());
  1567. UNIT_ASSERT(SqlToYql("pragma yson.DisableStrict;").IsOk());
  1568. }
  1569. Y_UNIT_TEST(YsonStrict) {
  1570. UNIT_ASSERT(SqlToYql("pragma yson.Strict = \"false\";").IsOk());
  1571. UNIT_ASSERT(SqlToYql("pragma yson.Strict;").IsOk());
  1572. }
  1573. Y_UNIT_TEST(JoinByTuple) {
  1574. auto req = "use plato;\n"
  1575. "\n"
  1576. "select * from T1 as a\n"
  1577. "join T2 as b\n"
  1578. "on AsTuple(a.key, a.subkey) = AsTuple(b.key, b.subkey);";
  1579. UNIT_ASSERT(SqlToYql(req).IsOk());
  1580. }
  1581. Y_UNIT_TEST(JoinByStruct) {
  1582. auto req = "use plato;\n"
  1583. "\n"
  1584. "select * from T1 as a\n"
  1585. "join T2 as b\n"
  1586. "on AsStruct(a.key as k, a.subkey as sk) = AsStruct(b.key as k, b.subkey as sk);";
  1587. UNIT_ASSERT(SqlToYql(req).IsOk());
  1588. }
  1589. Y_UNIT_TEST(JoinByUdf) {
  1590. auto req = "use plato;\n"
  1591. "\n"
  1592. "select a.align\n"
  1593. "from T1 as a\n"
  1594. "join T2 as b\n"
  1595. "on Yson::SerializeJsonEncodeUtf8(a.align)=b.align;";
  1596. UNIT_ASSERT(SqlToYql(req).IsOk());
  1597. }
  1598. Y_UNIT_TEST(EscapedIdentifierAsLambdaArg) {
  1599. auto req = "$f = ($`foo bar`, $x) -> { return $`foo bar` + $x; };\n"
  1600. "\n"
  1601. "select $f(1, 2);";
  1602. auto res = SqlToYql(req);
  1603. UNIT_ASSERT(res.Root);
  1604. const auto programm = GetPrettyPrint(res);
  1605. auto expected = "(lambda '(\"$foo bar\" \"$x\")";
  1606. UNIT_ASSERT(programm.find(expected) != TString::npos);
  1607. }
  1608. Y_UNIT_TEST(UdfSyntaxSugarOnlyCallable) {
  1609. auto req = "SELECT Udf(DateTime::FromString)('2022-01-01');";
  1610. auto res = SqlToYql(req);
  1611. UNIT_ASSERT(res.Root);
  1612. const auto programm = GetPrettyPrint(res);
  1613. auto expected = "(SqlCall '\"DateTime.FromString\" '((PositionalArgs (String '\"2022-01-01\")) (AsStruct)) (TupleType (TypeOf '((String '\"2022-01-01\"))) (TypeOf (AsStruct)) (TupleType)))";
  1614. UNIT_ASSERT(programm.find(expected) != TString::npos);
  1615. }
  1616. Y_UNIT_TEST(UdfSyntaxSugarTypeNoRun) {
  1617. auto req = "SELECT Udf(DateTime::FromString, String, Tuple<Int32, Float>, 'foo' as TypeConfig)('2022-01-01');";
  1618. auto res = SqlToYql(req);
  1619. UNIT_ASSERT(res.Root);
  1620. const auto programm = GetPrettyPrint(res);
  1621. auto expected = "(SqlCall '\"DateTime.FromString\" '((PositionalArgs (String '\"2022-01-01\")) (AsStruct)) (TupleType (TypeOf '((String '\"2022-01-01\"))) (TypeOf (AsStruct)) (TupleType (DataType 'String) (TupleType (DataType 'Int32) (DataType 'Float)))) '\"foo\")";
  1622. UNIT_ASSERT(programm.find(expected) != TString::npos);
  1623. }
  1624. Y_UNIT_TEST(UdfSyntaxSugarRunNoType) {
  1625. auto req = "SELECT Udf(DateTime::FromString, String, Tuple<Int32, Float>, Void() as RunConfig)('2022-01-01');";
  1626. auto res = SqlToYql(req);
  1627. UNIT_ASSERT(res.Root);
  1628. const auto programm = GetPrettyPrint(res);
  1629. auto expected = "(SqlCall '\"DateTime.FromString\" '((PositionalArgs (String '\"2022-01-01\")) (AsStruct)) (TupleType (TypeOf '((String '\"2022-01-01\"))) (TypeOf (AsStruct)) (TupleType (DataType 'String) (TupleType (DataType 'Int32) (DataType 'Float)))) '\"\" (Void))";
  1630. UNIT_ASSERT(programm.find(expected) != TString::npos);
  1631. }
  1632. Y_UNIT_TEST(UdfSyntaxSugarFullTest) {
  1633. auto req = "SELECT Udf(DateTime::FromString, String, Tuple<Int32, Float>, 'foo' as TypeConfig, Void() As RunConfig)('2022-01-01');";
  1634. auto res = SqlToYql(req);
  1635. UNIT_ASSERT(res.Root);
  1636. const auto programm = GetPrettyPrint(res);
  1637. auto expected = "(SqlCall '\"DateTime.FromString\" '((PositionalArgs (String '\"2022-01-01\")) (AsStruct)) (TupleType (TypeOf '((String '\"2022-01-01\"))) (TypeOf (AsStruct)) (TupleType (DataType 'String) (TupleType (DataType 'Int32) (DataType 'Float)))) '\"foo\" (Void))";
  1638. UNIT_ASSERT(programm.find(expected) != TString::npos);
  1639. }
  1640. Y_UNIT_TEST(UdfSyntaxSugarOtherRunConfigs) {
  1641. auto req = "SELECT Udf(DateTime::FromString, String, Tuple<Int32, Float>, 'foo' as TypeConfig, '55' As RunConfig)('2022-01-01');";
  1642. auto res = SqlToYql(req);
  1643. UNIT_ASSERT(res.Root);
  1644. const auto programm = GetPrettyPrint(res);
  1645. auto expected = "(SqlCall '\"DateTime.FromString\" '((PositionalArgs (String '\"2022-01-01\")) (AsStruct)) (TupleType (TypeOf '((String '\"2022-01-01\"))) (TypeOf (AsStruct)) (TupleType (DataType 'String) (TupleType (DataType 'Int32) (DataType 'Float)))) '\"foo\" (String '\"55\"))";
  1646. UNIT_ASSERT(programm.find(expected) != TString::npos);
  1647. }
  1648. Y_UNIT_TEST(UdfSyntaxSugarOtherRunConfigs2) {
  1649. auto req = "SELECT Udf(DateTime::FromString, String, Tuple<Int32, Float>, 'foo' as TypeConfig, AsTuple(32, 'no', AsStruct(1e-9 As SomeFloat)) As RunConfig)('2022-01-01');";
  1650. auto res = SqlToYql(req);
  1651. UNIT_ASSERT(res.Root);
  1652. const auto programm = GetPrettyPrint(res);
  1653. auto expected = "(SqlCall '\"DateTime.FromString\" '((PositionalArgs (String '\"2022-01-01\")) (AsStruct)) (TupleType (TypeOf '((String '\"2022-01-01\"))) (TypeOf (AsStruct)) (TupleType (DataType 'String) (TupleType (DataType 'Int32) (DataType 'Float)))) '\"foo\" '((Int32 '\"32\") (String '\"no\") (AsStruct '('\"SomeFloat\" (Double '\"1e-9\")))))";
  1654. UNIT_ASSERT(programm.find(expected) != TString::npos);
  1655. }
  1656. Y_UNIT_TEST(UdfSyntaxSugarOptional) {
  1657. auto req = "SELECT Udf(DateTime::FromString, String?, Int32??, Tuple<Int32, Float>, \"foo\" as TypeConfig, Void() As RunConfig)(\"2022-01-01\");";
  1658. auto res = SqlToYql(req);
  1659. UNIT_ASSERT(res.Root);
  1660. const auto programm = GetPrettyPrint(res);
  1661. auto expected = "(SqlCall '\"DateTime.FromString\" '((PositionalArgs (String '\"2022-01-01\")) (AsStruct)) (TupleType (TypeOf '((String '\"2022-01-01\"))) (TypeOf (AsStruct)) (TupleType (OptionalType (DataType 'String)) (OptionalType (OptionalType (DataType 'Int32))) (TupleType (DataType 'Int32) (DataType 'Float)))) '\"foo\" (Void))";
  1662. UNIT_ASSERT(programm.find(expected) != TString::npos);
  1663. }
  1664. Y_UNIT_TEST(CompactionPolicyParseCorrect) {
  1665. NYql::TAstParseResult res = SqlToYql(
  1666. R"( USE plato;
  1667. CREATE TABLE tableName (Key Uint32, Value String, PRIMARY KEY (Key))
  1668. WITH ( COMPACTION_POLICY = "SomeCompactionPreset" );)"
  1669. );
  1670. UNIT_ASSERT(res.Root);
  1671. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  1672. if (word == "Write") {
  1673. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("compactionPolicy"));
  1674. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("SomeCompactionPreset"));
  1675. }
  1676. };
  1677. TWordCountHive elementStat = { {TString("Write"), 0} };
  1678. VerifyProgram(res, elementStat, verifyLine);
  1679. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  1680. }
  1681. Y_UNIT_TEST(AutoPartitioningBySizeParseCorrect) {
  1682. NYql::TAstParseResult res = SqlToYql(
  1683. R"( USE plato;
  1684. CREATE TABLE tableName (Key Uint32, Value String, PRIMARY KEY (Key))
  1685. WITH ( AUTO_PARTITIONING_BY_SIZE = ENABLED );)"
  1686. );
  1687. UNIT_ASSERT(res.Root);
  1688. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  1689. if (word == "Write") {
  1690. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("autoPartitioningBySize"));
  1691. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("ENABLED"));
  1692. }
  1693. };
  1694. TWordCountHive elementStat = { {TString("Write"), 0} };
  1695. VerifyProgram(res, elementStat, verifyLine);
  1696. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  1697. }
  1698. Y_UNIT_TEST(UniformPartitionsParseCorrect) {
  1699. NYql::TAstParseResult res = SqlToYql(
  1700. R"( USE plato;
  1701. CREATE TABLE tableName (Key Uint32, Value String, PRIMARY KEY (Key))
  1702. WITH ( UNIFORM_PARTITIONS = 16 );)"
  1703. );
  1704. UNIT_ASSERT(res.Root);
  1705. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  1706. if (word == "Write") {
  1707. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("uniformPartitions"));
  1708. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("16"));
  1709. }
  1710. };
  1711. TWordCountHive elementStat = { {TString("Write"), 0} };
  1712. VerifyProgram(res, elementStat, verifyLine);
  1713. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  1714. }
  1715. Y_UNIT_TEST(DateTimeTtlParseCorrect) {
  1716. NYql::TAstParseResult res = SqlToYql(
  1717. R"( USE plato;
  1718. CREATE TABLE tableName (Key Uint32, CreatedAt Timestamp, PRIMARY KEY (Key))
  1719. WITH (TTL = Interval("P1D") On CreatedAt);)"
  1720. );
  1721. UNIT_ASSERT(res.Root);
  1722. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  1723. if (word == "Write") {
  1724. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("setTtlSettings"));
  1725. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("tiers"));
  1726. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("evictionDelay"));
  1727. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("86400000"));
  1728. }
  1729. };
  1730. TWordCountHive elementStat = { {TString("Write"), 0} };
  1731. VerifyProgram(res, elementStat, verifyLine);
  1732. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  1733. }
  1734. Y_UNIT_TEST(IntTtlParseCorrect) {
  1735. NYql::TAstParseResult res = SqlToYql(
  1736. R"( USE plato;
  1737. CREATE TABLE tableName (Key Uint32, CreatedAt Uint32, PRIMARY KEY (Key))
  1738. WITH (TTL = Interval("P1D") On CreatedAt AS SECONDS);)"
  1739. );
  1740. UNIT_ASSERT(res.Root);
  1741. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  1742. if (word == "Write") {
  1743. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("setTtlSettings"));
  1744. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("tiers"));
  1745. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("evictionDelay"));
  1746. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("86400000"));
  1747. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("columnUnit"));
  1748. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("seconds"));
  1749. }
  1750. };
  1751. TWordCountHive elementStat = { {TString("Write"), 0} };
  1752. VerifyProgram(res, elementStat, verifyLine);
  1753. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  1754. }
  1755. Y_UNIT_TEST(TtlTieringParseCorrect) {
  1756. NYql::TAstParseResult res = SqlToYql(
  1757. R"( USE plato;
  1758. CREATE TABLE tableName (Key Uint32, CreatedAt Uint32, PRIMARY KEY (Key))
  1759. WITH (TTL =
  1760. Interval("P1D") TO EXTERNAL DATA SOURCE Tier1,
  1761. Interval("P2D") TO EXTERNAL DATA SOURCE Tier2,
  1762. Interval("P30D") DELETE
  1763. On CreatedAt AS SECONDS);)"
  1764. );
  1765. UNIT_ASSERT(res.Root);
  1766. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  1767. if (word == "Write") {
  1768. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("setTtlSettings"));
  1769. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("tiers"));
  1770. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("evictionDelay"));
  1771. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("storageName"));
  1772. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("Tier1"));
  1773. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("Tier2"));
  1774. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("86400000"));
  1775. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("172800000"));
  1776. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("2592000000"));
  1777. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("columnUnit"));
  1778. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("seconds"));
  1779. }
  1780. };
  1781. TWordCountHive elementStat = { {TString("Write"), 0} };
  1782. VerifyProgram(res, elementStat, verifyLine);
  1783. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  1784. }
  1785. Y_UNIT_TEST(TtlTieringWithOtherActionsParseCorrect) {
  1786. NYql::TAstParseResult res = SqlToYql(
  1787. R"( USE plato;
  1788. ALTER TABLE tableName
  1789. ADD FAMILY cold (DATA = "rot"),
  1790. SET TTL
  1791. Interval("P1D") TO EXTERNAL DATA SOURCE Tier1,
  1792. Interval("P2D") TO EXTERNAL DATA SOURCE Tier2,
  1793. Interval("P30D") DELETE
  1794. ON CreatedAt,
  1795. ALTER COLUMN payload_v2 SET FAMILY cold,
  1796. ALTER FAMILY default SET DATA "ssd"
  1797. ;)"
  1798. );
  1799. UNIT_ASSERT(res.Root);
  1800. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  1801. if (word == "Write") {
  1802. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("addColumnFamilies"));
  1803. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("cold"));
  1804. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("alterColumnFamilies"));
  1805. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("default"));
  1806. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("setTtlSettings"));
  1807. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("tiers"));
  1808. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("evictionDelay"));
  1809. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("storageName"));
  1810. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("Tier1"));
  1811. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("Tier2"));
  1812. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("86400000"));
  1813. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("172800000"));
  1814. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("2592000000"));
  1815. }
  1816. };
  1817. TWordCountHive elementStat = { {TString("Write"), 0} };
  1818. VerifyProgram(res, elementStat, verifyLine);
  1819. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  1820. }
  1821. Y_UNIT_TEST(TieringParseCorrect) {
  1822. NYql::TAstParseResult res = SqlToYql(
  1823. R"( USE plato;
  1824. CREATE TABLE tableName (Key Uint32, Value String, PRIMARY KEY (Key))
  1825. WITH ( TIERING = 'my_tiering' );)"
  1826. );
  1827. UNIT_ASSERT(res.Root);
  1828. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  1829. if (word == "Write") {
  1830. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("tiering"));
  1831. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("my_tiering"));
  1832. }
  1833. };
  1834. TWordCountHive elementStat = { {TString("Write"), 0} };
  1835. VerifyProgram(res, elementStat, verifyLine);
  1836. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  1837. }
  1838. Y_UNIT_TEST(StoreExternalBlobsParseCorrect) {
  1839. NYql::TAstParseResult res = SqlToYql(
  1840. R"( USE plato;
  1841. CREATE TABLE tableName (Key Uint32, Value String, PRIMARY KEY (Key))
  1842. WITH ( STORE_EXTERNAL_BLOBS = ENABLED );)"
  1843. );
  1844. UNIT_ASSERT(res.Root);
  1845. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  1846. if (word == "Write") {
  1847. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("storeExternalBlobs"));
  1848. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("ENABLED"));
  1849. }
  1850. };
  1851. TWordCountHive elementStat = { {TString("Write"), 0} };
  1852. VerifyProgram(res, elementStat, verifyLine);
  1853. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  1854. }
  1855. Y_UNIT_TEST(DefaultValueColumn2) {
  1856. auto res = SqlToYql(R"( use plato;
  1857. $lambda = () -> {
  1858. RETURN CAST(RandomUuid(2) as String)
  1859. };
  1860. CREATE TABLE tableName (
  1861. Key Uint32 DEFAULT RandomNumber(1),
  1862. Value String DEFAULT $lambda,
  1863. PRIMARY KEY (Key)
  1864. );
  1865. )");
  1866. UNIT_ASSERT_C(res.Root, Err2Str(res));
  1867. const auto program = GetPrettyPrint(res);
  1868. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, program.find("RandomNumber"));
  1869. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, program.find("RandomUuid"));
  1870. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, program.find("columnConstrains"));
  1871. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, program.find("columnConstrains"));
  1872. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, program.find("Write"));
  1873. #if 0
  1874. Cerr << program << Endl;
  1875. #endif
  1876. TWordCountHive elementStat = { {TString("Write"), 0} };
  1877. VerifyProgram(res, elementStat);
  1878. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  1879. }
  1880. Y_UNIT_TEST(DefaultValueColumn3) {
  1881. auto res = SqlToYql(R"( use plato;
  1882. CREATE TABLE tableName (
  1883. database_id Utf8,
  1884. cloud_id Utf8,
  1885. global_id Utf8 DEFAULT database_id || "=====",
  1886. PRIMARY KEY (database_id)
  1887. );
  1888. )");
  1889. UNIT_ASSERT_VALUES_EQUAL(Err2Str(res), "<main>:6:40: Error: Column reference \"database_id\" is not allowed in current scope\n");
  1890. UNIT_ASSERT(!res.Root);
  1891. }
  1892. Y_UNIT_TEST(DefaultValueColumn) {
  1893. auto res = SqlToYql(R"( use plato;
  1894. CREATE TABLE tableName (
  1895. Key Uint32 FAMILY cold DEFAULT 5,
  1896. Value String FAMILY default DEFAULT "empty",
  1897. PRIMARY KEY (Key),
  1898. FAMILY default (
  1899. DATA = "test",
  1900. COMPRESSION = "lz4"
  1901. ),
  1902. FAMILY cold (
  1903. DATA = "test",
  1904. COMPRESSION = "off"
  1905. )
  1906. );
  1907. )");
  1908. UNIT_ASSERT_C(res.Root, Err2Str(res));
  1909. #if 0
  1910. const auto program = GetPrettyPrint(res);
  1911. Cerr << program << Endl;
  1912. #endif
  1913. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  1914. if (word == "Write") {
  1915. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("default"));
  1916. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("columnConstrains"));
  1917. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("columnFamilies"));
  1918. }
  1919. };
  1920. TWordCountHive elementStat = { {TString("Write"), 0} };
  1921. VerifyProgram(res, elementStat, verifyLine);
  1922. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  1923. }
  1924. Y_UNIT_TEST(ChangefeedParseCorrect) {
  1925. auto res = SqlToYql(R"( USE plato;
  1926. CREATE TABLE tableName (
  1927. Key Uint32, PRIMARY KEY (Key),
  1928. CHANGEFEED feedName WITH (
  1929. MODE = 'KEYS_ONLY',
  1930. FORMAT = 'json',
  1931. INITIAL_SCAN = TRUE,
  1932. VIRTUAL_TIMESTAMPS = FALSE,
  1933. RESOLVED_TIMESTAMPS = Interval("PT1S"),
  1934. RETENTION_PERIOD = Interval("P1D"),
  1935. TOPIC_MIN_ACTIVE_PARTITIONS = 10,
  1936. AWS_REGION = 'aws:region'
  1937. )
  1938. );
  1939. )");
  1940. UNIT_ASSERT_C(res.Root, Err2Str(res));
  1941. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  1942. if (word == "Write") {
  1943. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("changefeed"));
  1944. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("mode"));
  1945. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("KEYS_ONLY"));
  1946. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("format"));
  1947. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("json"));
  1948. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("initial_scan"));
  1949. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("true"));
  1950. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("virtual_timestamps"));
  1951. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("false"));
  1952. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("resolved_timestamps"));
  1953. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("retention_period"));
  1954. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("topic_min_active_partitions"));
  1955. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("aws_region"));
  1956. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("aws:region"));
  1957. }
  1958. };
  1959. TWordCountHive elementStat = { {TString("Write"), 0} };
  1960. VerifyProgram(res, elementStat, verifyLine);
  1961. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  1962. }
  1963. Y_UNIT_TEST(CloneForAsTableWorksWithCube) {
  1964. UNIT_ASSERT(SqlToYql("SELECT * FROM AS_TABLE([<|k1:1, k2:1|>]) GROUP BY CUBE(k1, k2);").IsOk());
  1965. }
  1966. Y_UNIT_TEST(WindowPartitionByColumnProperlyEscaped) {
  1967. NYql::TAstParseResult res = SqlToYql("SELECT SUM(key) OVER w FROM plato.Input WINDOW w AS (PARTITION BY `column with space`);");
  1968. UNIT_ASSERT(res.Root);
  1969. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  1970. if (word == "CalcOverWindow") {
  1971. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("\"column with space\""));
  1972. }
  1973. };
  1974. TWordCountHive elementStat = { {TString("CalcOverWindow"), 0} };
  1975. VerifyProgram(res, elementStat, verifyLine);
  1976. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["CalcOverWindow"]);
  1977. }
  1978. Y_UNIT_TEST(WindowPartitionByExpressionWithoutAliasesAreAllowed) {
  1979. NYql::TAstParseResult res = SqlToYql("SELECT SUM(key) OVER w FROM plato.Input as i WINDOW w AS (PARTITION BY ii.subkey);");
  1980. UNIT_ASSERT(res.Root);
  1981. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  1982. if (word == "AddMember") {
  1983. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("AddMember row 'group_w_0 (SqlAccess 'struct (Member row '\"ii\")"));
  1984. }
  1985. if (word == "CalcOverWindow") {
  1986. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("CalcOverWindow core '('\"group_w_0\")"));
  1987. }
  1988. };
  1989. TWordCountHive elementStat = { {TString("CalcOverWindow"), 0}, {TString("AddMember"), 0} };
  1990. VerifyProgram(res, elementStat, verifyLine);
  1991. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["CalcOverWindow"]);
  1992. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["AddMember"]);
  1993. }
  1994. Y_UNIT_TEST(PqReadByAfterUse) {
  1995. ExpectFailWithError("use plato; pragma PqReadBy='plato2';",
  1996. "<main>:1:28: Error: Cluster in PqReadPqBy pragma differs from cluster specified in USE statement: plato2 != plato\n");
  1997. UNIT_ASSERT(SqlToYql("pragma PqReadBy='plato2';").IsOk());
  1998. UNIT_ASSERT(SqlToYql("pragma PqReadBy='plato2'; use plato;").IsOk());
  1999. UNIT_ASSERT(SqlToYql("$x='plato'; use rtmr:$x; pragma PqReadBy='plato2';").IsOk());
  2000. UNIT_ASSERT(SqlToYql("use plato; pragma PqReadBy='dq';").IsOk());
  2001. }
  2002. Y_UNIT_TEST(MrObject) {
  2003. NYql::TAstParseResult res = SqlToYql(
  2004. "declare $path as String;\n"
  2005. "select * from plato.object($path, `format`, \"comp\" || \"ression\" as compression, 1 as bar) with schema (Int32 as y, String as x)"
  2006. );
  2007. UNIT_ASSERT(res.Root);
  2008. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  2009. if (word == "MrObject") {
  2010. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos,
  2011. line.find(R"__((MrObject (EvaluateAtom "$path") '"format" '('('"compression" (Concat (String '"comp") (String '"ression"))) '('"bar" (Int32 '"1")))))__"));
  2012. } else if (word == "userschema") {
  2013. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos,
  2014. line.find(R"__('('('"userschema" (StructType '('"y" (DataType 'Int32)) '('"x" (DataType 'String))) '('"y" '"x"))))__"));
  2015. }
  2016. };
  2017. TWordCountHive elementStat = {{TString("MrObject"), 0}, {TString("userschema"), 0}};
  2018. VerifyProgram(res, elementStat, verifyLine);
  2019. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["MrObject"]);
  2020. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["userschema"]);
  2021. }
  2022. Y_UNIT_TEST(TableBindings) {
  2023. NSQLTranslation::TTranslationSettings settings = GetSettingsWithS3Binding("foo");
  2024. NYql::TAstParseResult res = SqlToYqlWithSettings(
  2025. "select * from bindings.foo",
  2026. settings
  2027. );
  2028. UNIT_ASSERT(res.Root);
  2029. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  2030. if (word == "MrObject") {
  2031. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos,
  2032. line.find(R"__((MrTableConcat (Key '('table (String '"path")))) (Void) '('('"bar" '"1") '('"compression" '"ccompression") '('"format" '"format") '('"partitionedby" '"key" '"subkey") '('"userschema" (SqlTypeFromYson)__"));
  2033. }
  2034. };
  2035. TWordCountHive elementStat = {{TString("MrTableConcat"), 0}};
  2036. VerifyProgram(res, elementStat, verifyLine);
  2037. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["MrTableConcat"]);
  2038. settings.DefaultCluster = "plato";
  2039. settings.BindingsMode = NSQLTranslation::EBindingsMode::DISABLED;
  2040. res = SqlToYqlWithSettings(
  2041. "select * from bindings.foo",
  2042. settings
  2043. );
  2044. UNIT_ASSERT_VALUES_EQUAL(Err2Str(res), "<main>:1:15: Error: Please remove 'bindings.' from your query, the support for this syntax has ended, code: 4601\n");
  2045. UNIT_ASSERT(!res.Root);
  2046. settings.BindingsMode = NSQLTranslation::EBindingsMode::DROP;
  2047. res = SqlToYqlWithSettings(
  2048. "select * from bindings.foo",
  2049. settings
  2050. );
  2051. UNIT_ASSERT(res.Root);
  2052. TVerifyLineFunc verifyLine2 = [](const TString& word, const TString& line) {
  2053. if (word == "MrTableConcat") {
  2054. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos,
  2055. line.find(R"__((MrTableConcat (Key '('table (String '"foo")))) (Void) '())))__"));
  2056. }
  2057. };
  2058. TWordCountHive elementStat2 = {{TString("MrTableConcat"), 0}};
  2059. VerifyProgram(res, elementStat2, verifyLine2);
  2060. UNIT_ASSERT_VALUES_EQUAL(1, elementStat2["MrTableConcat"]);
  2061. settings.BindingsMode = NSQLTranslation::EBindingsMode::DROP_WITH_WARNING;
  2062. res = SqlToYqlWithSettings(
  2063. "select * from bindings.foo",
  2064. settings
  2065. );
  2066. UNIT_ASSERT_VALUES_EQUAL(Err2Str(res), "<main>:1:15: Warning: Please remove 'bindings.' from your query, the support for this syntax will be dropped soon, code: 4538\n");
  2067. UNIT_ASSERT(res.Root);
  2068. TWordCountHive elementStat3 = {{TString("MrTableConcat"), 0}};
  2069. VerifyProgram(res, elementStat3, verifyLine2);
  2070. UNIT_ASSERT_VALUES_EQUAL(1, elementStat3["MrTableConcat"]);
  2071. }
  2072. Y_UNIT_TEST(TableBindingsWithInsert) {
  2073. NSQLTranslation::TTranslationSettings settings = GetSettingsWithS3Binding("foo");
  2074. NYql::TAstParseResult res = SqlToYqlWithSettings(
  2075. "insert into bindings.foo with truncate (x, y) values (1, 2);",
  2076. settings
  2077. );
  2078. UNIT_ASSERT(res.Root);
  2079. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  2080. if (word == "Write!") {
  2081. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos,
  2082. line.find(R"__((Write! world sink (Key '('table (String '"path"))) values '('('"bar" '"1") '('"compression" '"ccompression") '('"format" '"format") '('"partitionedby" '"key" '"subkey") '('"userschema" (SqlTypeFromYson)__"));
  2083. }
  2084. };
  2085. TWordCountHive elementStat = {{TString("Write!"), 0}};
  2086. VerifyProgram(res, elementStat, verifyLine);
  2087. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write!"]);
  2088. settings.DefaultCluster = "plato";
  2089. settings.BindingsMode = NSQLTranslation::EBindingsMode::DISABLED;
  2090. res = SqlToYqlWithSettings(
  2091. "insert into bindings.foo with truncate (x, y) values (1, 2);",
  2092. settings
  2093. );
  2094. UNIT_ASSERT_VALUES_EQUAL(Err2Str(res), "<main>:1:13: Error: Please remove 'bindings.' from your query, the support for this syntax has ended, code: 4601\n");
  2095. UNIT_ASSERT(!res.Root);
  2096. settings.BindingsMode = NSQLTranslation::EBindingsMode::DROP;
  2097. res = SqlToYqlWithSettings(
  2098. "insert into bindings.foo with truncate (x, y) values (1, 2);",
  2099. settings
  2100. );
  2101. UNIT_ASSERT_VALUES_EQUAL(Err2Str(res), "");
  2102. UNIT_ASSERT(res.Root);
  2103. TVerifyLineFunc verifyLine2 = [](const TString& word, const TString& line) {
  2104. if (word == "Write!") {
  2105. //UNIT_ASSERT_VALUES_EQUAL(line, "");
  2106. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos,
  2107. line.find(R"__((Write! world sink (Key '('table (String '"foo"))) values '('('mode 'renew)))__"));
  2108. }
  2109. };
  2110. TWordCountHive elementStat2 = {{TString("Write!"), 0}};
  2111. VerifyProgram(res, elementStat2, verifyLine2);
  2112. UNIT_ASSERT_VALUES_EQUAL(1, elementStat2["Write!"]);
  2113. settings.BindingsMode = NSQLTranslation::EBindingsMode::DROP_WITH_WARNING;
  2114. res = SqlToYqlWithSettings(
  2115. "insert into bindings.foo with truncate (x, y) values (1, 2);",
  2116. settings
  2117. );
  2118. UNIT_ASSERT_VALUES_EQUAL(Err2Str(res), "<main>:1:13: Warning: Please remove 'bindings.' from your query, the support for this syntax will be dropped soon, code: 4538\n");
  2119. UNIT_ASSERT(res.Root);
  2120. TWordCountHive elementStat3 = {{TString("Write!"), 0}};
  2121. VerifyProgram(res, elementStat3, verifyLine2);
  2122. UNIT_ASSERT_VALUES_EQUAL(1, elementStat3["Write!"]);
  2123. }
  2124. Y_UNIT_TEST(TrailingCommaInWithout) {
  2125. UNIT_ASSERT(SqlToYql("SELECT * WITHOUT stream, FROM plato.Input").IsOk());
  2126. UNIT_ASSERT(SqlToYql("SELECT a.* WITHOUT a.intersect, FROM plato.Input AS a").IsOk());
  2127. UNIT_ASSERT(SqlToYql("SELECT a.* WITHOUT col1, col2, a.col3, FROM plato.Input AS a").IsOk());
  2128. }
  2129. Y_UNIT_TEST(NoStackOverflowOnBigCaseStatement) {
  2130. TStringBuilder req;
  2131. req << "select case 1 + 123";
  2132. for (size_t i = 0; i < 20000; ++i) {
  2133. req << " when " << i << " then " << i + 1;
  2134. }
  2135. req << " else 100500 end;";
  2136. UNIT_ASSERT(SqlToYql(req).IsOk());
  2137. }
  2138. Y_UNIT_TEST(CollectPreaggregatedInListLiteral) {
  2139. UNIT_ASSERT(SqlToYql("SELECT [COUNT(DISTINCT a+b)] FROM plato.Input").IsOk());
  2140. }
  2141. Y_UNIT_TEST(SmartParenInGroupByClause) {
  2142. UNIT_ASSERT(SqlToYql("SELECT * FROM plato.Input GROUP BY (k, v)").IsOk());
  2143. }
  2144. Y_UNIT_TEST(AlterTableRenameToIsCorrect) {
  2145. UNIT_ASSERT(SqlToYql("USE plato; ALTER TABLE table RENAME TO moved").IsOk());
  2146. }
  2147. Y_UNIT_TEST(AlterTableAddDropColumnIsCorrect) {
  2148. UNIT_ASSERT(SqlToYql("USE plato; ALTER TABLE table ADD COLUMN addc uint64, DROP COLUMN dropc, ADD addagain uint64").IsOk());
  2149. }
  2150. Y_UNIT_TEST(AlterTableSetTTLIsCorrect) {
  2151. UNIT_ASSERT(SqlToYql("USE plato; ALTER TABLE table SET (TTL = Interval(\"PT3H\") ON column)").IsOk());
  2152. UNIT_ASSERT(SqlToYql("USE plato; ALTER TABLE table SET (TTL = Interval(\"PT3H\") ON column AS SECONDS)").IsOk());
  2153. }
  2154. Y_UNIT_TEST(AlterTableSetTieringIsCorrect) {
  2155. UNIT_ASSERT(SqlToYql("USE plato; ALTER TABLE table SET (TIERING = 'my_tiering')").IsOk());
  2156. }
  2157. Y_UNIT_TEST(AlterTableAddChangefeedIsCorrect) {
  2158. UNIT_ASSERT(SqlToYql("USE plato; ALTER TABLE table ADD CHANGEFEED feed WITH (MODE = 'UPDATES', FORMAT = 'json')").IsOk());
  2159. }
  2160. Y_UNIT_TEST(AlterTableAlterChangefeedIsCorrect) {
  2161. UNIT_ASSERT(SqlToYql("USE plato; ALTER TABLE table ALTER CHANGEFEED feed DISABLE").IsOk());
  2162. ExpectFailWithError("USE plato; ALTER TABLE table ALTER CHANGEFEED feed SET (FORMAT = 'proto');",
  2163. "<main>:1:57: Error: FORMAT alter is not supported\n");
  2164. }
  2165. Y_UNIT_TEST(AlterTableDropChangefeedIsCorrect) {
  2166. UNIT_ASSERT(SqlToYql("USE plato; ALTER TABLE table DROP CHANGEFEED feed").IsOk());
  2167. }
  2168. Y_UNIT_TEST(AlterTableSetPartitioningIsCorrect) {
  2169. UNIT_ASSERT(SqlToYql("USE plato; ALTER TABLE table SET (AUTO_PARTITIONING_BY_SIZE = DISABLED)").IsOk());
  2170. }
  2171. Y_UNIT_TEST(AlterTableAddIndexWithIsNotSupported) {
  2172. ExpectFailWithError("USE plato; ALTER TABLE table ADD INDEX idx GLOBAL ON (col) WITH (a=b)",
  2173. "<main>:1:40: Error: with: alternative is not implemented yet: \n");
  2174. }
  2175. Y_UNIT_TEST(AlterTableAddIndexLocalIsNotSupported) {
  2176. ExpectFailWithError("USE plato; ALTER TABLE table ADD INDEX idx LOCAL ON (col)",
  2177. "<main>:1:40: Error: local: alternative is not implemented yet: \n");
  2178. }
  2179. Y_UNIT_TEST(CreateTableAddIndexVector) {
  2180. const auto result = SqlToYql(R"(USE plato;
  2181. CREATE TABLE table (
  2182. pk INT32 NOT NULL,
  2183. col String,
  2184. INDEX idx GLOBAL USING vector_kmeans_tree
  2185. ON (col) COVER (col)
  2186. WITH (distance=cosine, vector_type=float, vector_dimension=1024,),
  2187. PRIMARY KEY (pk))
  2188. )");
  2189. UNIT_ASSERT_C(result.IsOk(), result.Issues.ToString());
  2190. }
  2191. Y_UNIT_TEST(AlterTableAddIndexVector) {
  2192. const auto result = SqlToYql(R"(USE plato;
  2193. ALTER TABLE table ADD INDEX idx
  2194. GLOBAL USING vector_kmeans_tree
  2195. ON (col) COVER (col)
  2196. WITH (distance=cosine, vector_type="float", vector_dimension=1024)
  2197. )");
  2198. UNIT_ASSERT_C(result.IsOk(), result.Issues.ToString());
  2199. }
  2200. Y_UNIT_TEST(AlterTableAddIndexUnknownSubtype) {
  2201. ExpectFailWithError("USE plato; ALTER TABLE table ADD INDEX idx GLOBAL USING unknown ON (col)",
  2202. "<main>:1:57: Error: UNKNOWN index subtype is not supported\n");
  2203. }
  2204. Y_UNIT_TEST(AlterTableAddIndexMissedParameter) {
  2205. ExpectFailWithError(R"(USE plato;
  2206. ALTER TABLE table ADD INDEX idx
  2207. GLOBAL USING vector_kmeans_tree
  2208. ON (col)
  2209. WITH (distance=cosine, vector_type=float)
  2210. )",
  2211. "<main>:5:52: Error: vector_dimension should be set\n");
  2212. }
  2213. Y_UNIT_TEST(AlterTableAlterIndexSetPartitioningIsCorrect) {
  2214. const auto result = SqlToYql("USE plato; ALTER TABLE table ALTER INDEX index SET AUTO_PARTITIONING_MIN_PARTITIONS_COUNT 10");
  2215. UNIT_ASSERT_C(result.IsOk(), result.Issues.ToString());
  2216. }
  2217. Y_UNIT_TEST(AlterTableAlterIndexSetMultiplePartitioningSettings) {
  2218. const auto result = SqlToYql("USE plato; ALTER TABLE table ALTER INDEX index SET "
  2219. "(AUTO_PARTITIONING_BY_LOAD = ENABLED, AUTO_PARTITIONING_MIN_PARTITIONS_COUNT = 10)"
  2220. );
  2221. UNIT_ASSERT_C(result.IsOk(), result.Issues.ToString());
  2222. }
  2223. Y_UNIT_TEST(AlterTableAlterIndexResetPartitioningIsNotSupported) {
  2224. ExpectFailWithError("USE plato; ALTER TABLE table ALTER INDEX index RESET (AUTO_PARTITIONING_MIN_PARTITIONS_COUNT)",
  2225. "<main>:1:55: Error: AUTO_PARTITIONING_MIN_PARTITIONS_COUNT reset is not supported\n"
  2226. );
  2227. }
  2228. Y_UNIT_TEST(AlterTableAlterColumnDropNotNullAstCorrect) {
  2229. auto reqSetNull = SqlToYql(R"(
  2230. USE plato;
  2231. CREATE TABLE tableName (
  2232. id Uint32,
  2233. val Uint32 NOT NULL,
  2234. PRIMARY KEY (id)
  2235. );
  2236. COMMIT;
  2237. ALTER TABLE tableName ALTER COLUMN val DROP NOT NULL;
  2238. )");
  2239. UNIT_ASSERT(reqSetNull.IsOk());
  2240. UNIT_ASSERT(reqSetNull.Root);
  2241. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  2242. Y_UNUSED(word);
  2243. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(
  2244. R"(let world (Write! world sink (Key '('tablescheme (String '"tableName"))) (Void) '('('mode 'alter) '('actions '('('alterColumns '('('"val" '('changeColumnConstraints '('('drop_not_null)))))))))))"
  2245. ));
  2246. };
  2247. TWordCountHive elementStat({TString("\'mode \'alter")});
  2248. VerifyProgram(reqSetNull, elementStat, verifyLine);
  2249. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["\'mode \'alter"]);
  2250. }
  2251. Y_UNIT_TEST(AlterSequence) {
  2252. UNIT_ASSERT(SqlToYql(R"(
  2253. USE plato;
  2254. ALTER SEQUENCE sequence START WITH 10 INCREMENT 2 RESTART WITH 5;
  2255. )").IsOk());
  2256. UNIT_ASSERT(SqlToYql(R"(
  2257. USE plato;
  2258. ALTER SEQUENCE sequence INCREMENT 2;
  2259. )").IsOk());
  2260. UNIT_ASSERT(SqlToYql(R"(
  2261. USE plato;
  2262. ALTER SEQUENCE sequence INCREMENT 2 START 1000;
  2263. )").IsOk());
  2264. UNIT_ASSERT(SqlToYql(R"(
  2265. USE plato;
  2266. ALTER SEQUENCE sequence RESTART START 1000;
  2267. )").IsOk());
  2268. UNIT_ASSERT(SqlToYql(R"(
  2269. USE plato;
  2270. ALTER SEQUENCE IF EXISTS sequence INCREMENT 1000 START 100 RESTART;
  2271. )").IsOk());
  2272. UNIT_ASSERT(SqlToYql(R"(
  2273. USE plato;
  2274. ALTER SEQUENCE IF EXISTS sequence RESTART 1000 START WITH 100 INCREMENT BY 7;
  2275. )").IsOk());
  2276. }
  2277. Y_UNIT_TEST(AlterSequenceIncorrect) {
  2278. {
  2279. NYql::TAstParseResult res = SqlToYql("USE plato; ALTER SEQUENCE sequence START WITH 10 INCREMENT 2 RESTART WITH 5 RESTART;");
  2280. UNIT_ASSERT(!res.Root);
  2281. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:75: Error: Restart value defined more than once\n");
  2282. }
  2283. {
  2284. NYql::TAstParseResult res = SqlToYql("USE plato; ALTER SEQUENCE sequence START WITH 10 INCREMENT 2 START 100 RESTART WITH 5;");
  2285. UNIT_ASSERT(!res.Root);
  2286. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:60: Error: Start value defined more than once\n");
  2287. }
  2288. {
  2289. NYql::TAstParseResult res = SqlToYql("USE plato; ALTER SEQUENCE sequence INCREMENT BY 7 START WITH 10 INCREMENT 2 RESTART WITH 5 RESTART;");
  2290. UNIT_ASSERT(!res.Root);
  2291. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:62: Error: Increment defined more than once\n");
  2292. }
  2293. {
  2294. NYql::TAstParseResult res = SqlToYql("USE plato; ALTER SEQUENCE sequence RESTART WITH 100 START WITH 10 INCREMENT 2 RESTART WITH 5;");
  2295. UNIT_ASSERT(!res.Root);
  2296. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:77: Error: Restart value defined more than once\n");
  2297. }
  2298. {
  2299. NYql::TAstParseResult res = SqlToYql("USE plato; ALTER SEQUENCE sequence RESTART WITH 1234234543563435151456 START WITH 10 INCREMENT 2;");
  2300. UNIT_ASSERT(!res.Root);
  2301. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:49: Error: Failed to parse number from string: 1234234543563435151456, number limit overflow\n");
  2302. }
  2303. {
  2304. NYql::TAstParseResult res = SqlToYql("USE plato; ALTER SEQUENCE sequence RESTART WITH 1 START WITH 9223372036854775817 INCREMENT 4;");
  2305. UNIT_ASSERT(!res.Root);
  2306. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:12: Error: Start value: 9223372036854775817 cannot be greater than max value: 9223372036854775807\n");
  2307. }
  2308. {
  2309. NYql::TAstParseResult res = SqlToYql("USE plato; ALTER SEQUENCE sequence RESTART WITH 9223372036854775827 START WITH 5 INCREMENT 4;");
  2310. UNIT_ASSERT(!res.Root);
  2311. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:12: Error: Restart value: 9223372036854775827 cannot be greater than max value: 9223372036854775807\n");
  2312. }
  2313. {
  2314. NYql::TAstParseResult res = SqlToYql("USE plato; ALTER SEQUENCE sequence RESTART WITH 1 START WITH 4 INCREMENT 0;");
  2315. UNIT_ASSERT(!res.Root);
  2316. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:12: Error: Increment must not be zero\n");
  2317. }
  2318. {
  2319. NYql::TAstParseResult res = SqlToYql("USE plato; ALTER SEQUENCE sequence RESTART WITH 0 START WITH 4 INCREMENT 1;");
  2320. UNIT_ASSERT(!res.Root);
  2321. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:12: Error: Restart value: 0 cannot be less than min value: 1\n");
  2322. }
  2323. {
  2324. NYql::TAstParseResult res = SqlToYql("USE plato; ALTER SEQUENCE sequence RESTART WITH 1 START WITH 0 INCREMENT 1;");
  2325. UNIT_ASSERT(!res.Root);
  2326. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:12: Error: Start value: 0 cannot be less than min value: 1\n");
  2327. }
  2328. {
  2329. NYql::TAstParseResult res = SqlToYql("USE plato; ALTER SEQUENCE sequence RESTART WITH 1 START WITH 1 INCREMENT 9223372036854775837;");
  2330. UNIT_ASSERT(!res.Root);
  2331. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:12: Error: Increment: 9223372036854775837 cannot be greater than max value: 9223372036854775807\n");
  2332. }
  2333. }
  2334. Y_UNIT_TEST(AlterSequenceCorrect) {
  2335. {
  2336. NYql::TAstParseResult res = SqlToYql("USE plato; ALTER SEQUENCE sequence START WITH 10 INCREMENT 2 RESTART WITH 5;");
  2337. UNIT_ASSERT(res.Root);
  2338. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  2339. if (word == "Write") {
  2340. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("sequence"));
  2341. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("alter"));
  2342. UNIT_ASSERT_VALUES_EQUAL(TString::npos, line.find("alter_if_exists"));
  2343. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("start"));
  2344. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("increment"));
  2345. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("restart"));
  2346. }
  2347. };
  2348. TWordCountHive elementStat = { {TString("Write"), 0}};
  2349. VerifyProgram(res, elementStat, verifyLine);
  2350. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  2351. }
  2352. {
  2353. NYql::TAstParseResult res = SqlToYql("USE plato; ALTER SEQUENCE IF EXISTS sequence INCREMENT 2 RESTART;");
  2354. UNIT_ASSERT(res.Root);
  2355. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  2356. if (word == "Write") {
  2357. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("sequence"));
  2358. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("alter_if_exists"));
  2359. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("increment"));
  2360. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("restart"));
  2361. }
  2362. };
  2363. TWordCountHive elementStat = { {TString("Write"), 0}};
  2364. VerifyProgram(res, elementStat, verifyLine);
  2365. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  2366. }
  2367. {
  2368. NYql::TAstParseResult res = SqlToYql("USE plato; ALTER SEQUENCE IF EXISTS sequence START 10 INCREMENT BY 2;");
  2369. UNIT_ASSERT(res.Root);
  2370. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  2371. if (word == "Write") {
  2372. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("sequence"));
  2373. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("alter_if_exists"));
  2374. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("start"));
  2375. UNIT_ASSERT_VALUES_EQUAL(TString::npos, line.find("restart"));
  2376. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("increment"));
  2377. }
  2378. };
  2379. TWordCountHive elementStat = { {TString("Write"), 0}};
  2380. VerifyProgram(res, elementStat, verifyLine);
  2381. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  2382. }
  2383. }
  2384. Y_UNIT_TEST(OptionalAliases) {
  2385. UNIT_ASSERT(SqlToYql("USE plato; SELECT foo FROM (SELECT key foo FROM Input);").IsOk());
  2386. UNIT_ASSERT(SqlToYql("USE plato; SELECT a.x FROM Input1 a JOIN Input2 b ON a.key = b.key;").IsOk());
  2387. UNIT_ASSERT(SqlToYql("USE plato; SELECT a.x FROM (VALUES (1,2), (3,4)) a(x,key) JOIN Input b ON a.key = b.key;").IsOk());
  2388. }
  2389. Y_UNIT_TEST(TableNameConstness) {
  2390. UNIT_ASSERT(SqlToYql("USE plato; $path = 'foo'; SELECT TableName($path), count(*) FROM Input;").IsOk());
  2391. UNIT_ASSERT(SqlToYql("$path = 'foo'; SELECT TableName($path, 'yt'), count(*) FROM plato.Input;").IsOk());
  2392. ExpectFailWithError("USE plato; SELECT TableName(), count(*) FROM plato.Input;",
  2393. "<main>:1:19: Error: Expression has to be an aggregation function or key column, because aggregation is used elsewhere in this subquery\n");
  2394. }
  2395. Y_UNIT_TEST(UseShouldWorkAsColumnName) {
  2396. UNIT_ASSERT(SqlToYql("select use from (select 1 as use);").IsOk());
  2397. }
  2398. Y_UNIT_TEST(TrueFalseWorkAfterDollar) {
  2399. UNIT_ASSERT(SqlToYql("$ true = false; SELECT $ true or false;").IsOk());
  2400. UNIT_ASSERT(SqlToYql("$False = 0; SELECT $False;").IsOk());
  2401. }
  2402. Y_UNIT_TEST(WithSchemaEquals) {
  2403. UNIT_ASSERT(SqlToYql("select * from plato.T with schema Struct<a:Int32, b:String>;").IsOk());
  2404. UNIT_ASSERT(SqlToYql("select * from plato.T with columns = Struct<a:Int32, b:String>;").IsOk());
  2405. }
  2406. Y_UNIT_TEST(WithNonStructSchemaS3) {
  2407. NSQLTranslation::TTranslationSettings settings;
  2408. settings.ClusterMapping["s3bucket"] = NYql::S3ProviderName;
  2409. UNIT_ASSERT(SqlToYql("select * from s3bucket.`foo` with schema (col1 Int32, String as col2, Int64 as col3);", settings).IsOk());
  2410. }
  2411. Y_UNIT_TEST(AllowNestedTuplesInGroupBy) {
  2412. NYql::TAstParseResult res = SqlToYql("select count(*) from plato.Input group by 1 + (x, y, z);");
  2413. UNIT_ASSERT(res.Root);
  2414. TVerifyLineFunc verifyLine = [&](const TString& word, const TString& line) {
  2415. Y_UNUSED(word);
  2416. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("(Aggregate core '('\"group0\")"));
  2417. };
  2418. TWordCountHive elementStat({"Aggregate"});
  2419. VerifyProgram(res, elementStat, verifyLine);
  2420. UNIT_ASSERT(elementStat["Aggregate"] == 1);
  2421. }
  2422. Y_UNIT_TEST(AllowGroupByWithParens) {
  2423. NYql::TAstParseResult res = SqlToYql("select count(*) from plato.Input group by (x, y as alias1, z);");
  2424. UNIT_ASSERT(res.Root);
  2425. TVerifyLineFunc verifyLine = [&](const TString& word, const TString& line) {
  2426. Y_UNUSED(word);
  2427. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("(Aggregate core '('\"x\" '\"alias1\" '\"z\")"));
  2428. };
  2429. TWordCountHive elementStat({"Aggregate"});
  2430. VerifyProgram(res, elementStat, verifyLine);
  2431. UNIT_ASSERT(elementStat["Aggregate"] == 1);
  2432. }
  2433. Y_UNIT_TEST(CreateAsyncReplicationParseCorrect) {
  2434. auto req = R"(
  2435. USE plato;
  2436. CREATE ASYNC REPLICATION MyReplication
  2437. FOR table1 AS table2, table3 AS table4
  2438. WITH (
  2439. CONNECTION_STRING = "grpc://localhost:2135/?database=/MyDatabase",
  2440. ENDPOINT = "localhost:2135",
  2441. DATABASE = "/MyDatabase"
  2442. );
  2443. )";
  2444. auto res = SqlToYql(req);
  2445. UNIT_ASSERT(res.Root);
  2446. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  2447. if (word == "Write") {
  2448. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("MyReplication"));
  2449. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("create"));
  2450. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("table1"));
  2451. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("table2"));
  2452. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("table3"));
  2453. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("table4"));
  2454. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("connection_string"));
  2455. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("grpc://localhost:2135/?database=/MyDatabase"));
  2456. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("endpoint"));
  2457. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("localhost:2135"));
  2458. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("database"));
  2459. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("/MyDatabase"));
  2460. }
  2461. };
  2462. TWordCountHive elementStat = { {TString("Write"), 0}};
  2463. VerifyProgram(res, elementStat, verifyLine);
  2464. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  2465. }
  2466. Y_UNIT_TEST(CreateAsyncReplicationUnsupportedSettings) {
  2467. auto reqTpl = R"(
  2468. USE plato;
  2469. CREATE ASYNC REPLICATION MyReplication
  2470. FOR table1 AS table2, table3 AS table4
  2471. WITH (
  2472. %s = "%s"
  2473. )
  2474. )";
  2475. auto settings = THashMap<TString, TString>{
  2476. {"STATE", "DONE"},
  2477. {"FAILOVER_MODE", "FORCE"},
  2478. };
  2479. for (const auto& [k, v] : settings) {
  2480. auto req = Sprintf(reqTpl, k.c_str(), v.c_str());
  2481. auto res = SqlToYql(req);
  2482. UNIT_ASSERT(!res.Root);
  2483. UNIT_ASSERT_NO_DIFF(Err2Str(res), Sprintf("<main>:6:%zu: Error: %s is not supported in CREATE\n", 20 + k.size(), k.c_str()));
  2484. }
  2485. }
  2486. Y_UNIT_TEST(AlterAsyncReplicationParseCorrect) {
  2487. auto req = R"(
  2488. USE plato;
  2489. ALTER ASYNC REPLICATION MyReplication
  2490. SET (
  2491. STATE = "DONE",
  2492. FAILOVER_MODE = "FORCE"
  2493. );
  2494. )";
  2495. auto res = SqlToYql(req);
  2496. UNIT_ASSERT(res.Root);
  2497. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  2498. if (word == "Write") {
  2499. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("MyReplication"));
  2500. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("alter"));
  2501. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("state"));
  2502. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("DONE"));
  2503. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("failover_mode"));
  2504. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("FORCE"));
  2505. }
  2506. };
  2507. TWordCountHive elementStat = { {TString("Write"), 0}};
  2508. VerifyProgram(res, elementStat, verifyLine);
  2509. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  2510. }
  2511. Y_UNIT_TEST(AlterAsyncReplicationUnsupportedSettings) {
  2512. auto reqTpl = R"(
  2513. USE plato;
  2514. ALTER ASYNC REPLICATION MyReplication
  2515. SET (
  2516. %s = "%s"
  2517. )
  2518. )";
  2519. auto settings = THashMap<TString, TString>{
  2520. {"connection_string", "grpc://localhost:2135/?database=/MyDatabase"},
  2521. {"endpoint", "localhost:2135"},
  2522. {"database", "/MyDatabase"},
  2523. {"token", "foo"},
  2524. {"token_secret_name", "foo_secret_name"},
  2525. {"user", "user"},
  2526. {"password", "bar"},
  2527. {"password_secret_name", "bar_secret_name"},
  2528. };
  2529. for (const auto& setting : settings) {
  2530. auto& key = setting.first;
  2531. auto& value = setting.second;
  2532. auto req = Sprintf(reqTpl, key.c_str(), value.c_str());
  2533. auto res = SqlToYql(req);
  2534. UNIT_ASSERT(res.Root);
  2535. TVerifyLineFunc verifyLine = [&key, &value](const TString& word, const TString& line) {
  2536. if (word == "Write") {
  2537. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("MyReplication"));
  2538. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("alter"));
  2539. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(key));
  2540. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(value));
  2541. }
  2542. };
  2543. TWordCountHive elementStat = { {TString("Write"), 0}};
  2544. VerifyProgram(res, elementStat, verifyLine);
  2545. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  2546. }
  2547. }
  2548. Y_UNIT_TEST(AsyncReplicationInvalidSettings) {
  2549. auto req = R"(
  2550. USE plato;
  2551. ALTER ASYNC REPLICATION MyReplication SET (FOO = "BAR");
  2552. )";
  2553. auto res = SqlToYql(req);
  2554. UNIT_ASSERT(!res.Root);
  2555. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:3:62: Error: Unknown replication setting: FOO\n");
  2556. }
  2557. Y_UNIT_TEST(DropAsyncReplicationParseCorrect) {
  2558. auto req = R"(
  2559. USE plato;
  2560. DROP ASYNC REPLICATION MyReplication;
  2561. )";
  2562. auto res = SqlToYql(req);
  2563. UNIT_ASSERT(res.Root);
  2564. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  2565. if (word == "Write") {
  2566. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("MyReplication"));
  2567. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("drop"));
  2568. }
  2569. };
  2570. TWordCountHive elementStat = { {TString("Write"), 0}};
  2571. VerifyProgram(res, elementStat, verifyLine);
  2572. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  2573. }
  2574. Y_UNIT_TEST(DropAsyncReplicationCascade) {
  2575. auto req = R"(
  2576. USE plato;
  2577. DROP ASYNC REPLICATION MyReplication CASCADE;
  2578. )";
  2579. auto res = SqlToYql(req);
  2580. UNIT_ASSERT(res.Root);
  2581. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  2582. if (word == "Write") {
  2583. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("dropCascade"));
  2584. }
  2585. };
  2586. TWordCountHive elementStat = { {TString("Write"), 0}};
  2587. VerifyProgram(res, elementStat, verifyLine);
  2588. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  2589. }
  2590. Y_UNIT_TEST(PragmaCompactGroupBy) {
  2591. auto req = "PRAGMA CompactGroupBy; SELECT key, COUNT(*) FROM plato.Input GROUP BY key;";
  2592. auto res = SqlToYql(req);
  2593. UNIT_ASSERT(res.Root);
  2594. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  2595. if (word == "Aggregate") {
  2596. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("'('compact)"));
  2597. }
  2598. };
  2599. TWordCountHive elementStat = { {TString("Aggregate"), 0}};
  2600. VerifyProgram(res, elementStat, verifyLine);
  2601. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Aggregate"]);
  2602. }
  2603. Y_UNIT_TEST(PragmaDisableCompactGroupBy) {
  2604. auto req = "PRAGMA DisableCompactGroupBy; SELECT key, COUNT(*) FROM plato.Input GROUP /*+ compact() */ BY key;";
  2605. auto res = SqlToYql(req);
  2606. UNIT_ASSERT(res.Root);
  2607. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  2608. if (word == "Aggregate") {
  2609. UNIT_ASSERT_VALUES_EQUAL(TString::npos, line.find("'('compact)"));
  2610. }
  2611. };
  2612. TWordCountHive elementStat = { {TString("Aggregate"), 0}};
  2613. VerifyProgram(res, elementStat, verifyLine);
  2614. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Aggregate"]);
  2615. }
  2616. Y_UNIT_TEST(AutoSampleWorksWithNamedSubquery) {
  2617. UNIT_ASSERT(SqlToYql("$src = select * from plato.Input; select * from $src sample 0.2").IsOk());
  2618. }
  2619. Y_UNIT_TEST(AutoSampleWorksWithSubquery) {
  2620. UNIT_ASSERT(SqlToYql("select * from (select * from plato.Input) sample 0.2").IsOk());
  2621. }
  2622. Y_UNIT_TEST(CreateTableTrailingComma) {
  2623. UNIT_ASSERT(SqlToYql("USE plato; CREATE TABLE tableName (Key Uint32, PRIMARY KEY (Key),);").IsOk());
  2624. UNIT_ASSERT(SqlToYql("USE plato; CREATE TABLE tableName (Key Uint32,);").IsOk());
  2625. }
  2626. Y_UNIT_TEST(BetweenSymmetric) {
  2627. UNIT_ASSERT(SqlToYql("select 3 between symmetric 5 and 4;").IsOk());
  2628. UNIT_ASSERT(SqlToYql("select 3 between asymmetric 5 and 4;").IsOk());
  2629. UNIT_ASSERT(SqlToYql("use plato; select key between symmetric and and and from Input;").IsOk());
  2630. UNIT_ASSERT(SqlToYql("use plato; select key between and and and from Input;").IsOk());
  2631. }
  2632. }
  2633. Y_UNIT_TEST_SUITE(ExternalFunction) {
  2634. Y_UNIT_TEST(ValidUseFunctions) {
  2635. UNIT_ASSERT(SqlToYql(
  2636. "PROCESS plato.Input"
  2637. " USING EXTERNAL FUNCTION('YANDEX-CLOUD', 'foo', <|a: 123, b: a + 641|>)"
  2638. " WITH INPUT_TYPE=Struct<a:Int32>, OUTPUT_TYPE=Struct<b:Int32>,"
  2639. " CONCURRENCY=3, OPTIMIZE_FOR='CALLS'").IsOk());
  2640. // use CALLS without quotes, as keyword
  2641. UNIT_ASSERT(SqlToYql(
  2642. "PROCESS plato.Input"
  2643. " USING EXTERNAL FUNCTION('YANDEX-CLOUD', 'foo')"
  2644. " WITH INPUT_TYPE=Struct<a:Int32>, OUTPUT_TYPE=Struct<b:Int32>,"
  2645. " OPTIMIZE_FOR=CALLS").IsOk());
  2646. UNIT_ASSERT(SqlToYql(
  2647. "PROCESS plato.Input"
  2648. " USING EXTERNAL FUNCTION('YANDEX-CLOUD', 'foo', TableRow())"
  2649. " WITH INPUT_TYPE=Struct<a:Int32>, OUTPUT_TYPE=Struct<b:Int32>,"
  2650. " CONCURRENCY=3").IsOk());
  2651. UNIT_ASSERT(SqlToYql(
  2652. "PROCESS plato.Input"
  2653. " USING EXTERNAL FUNCTION('YANDEX-CLOUD', 'foo')"
  2654. " WITH INPUT_TYPE=Struct<a:Int32>, OUTPUT_TYPE=Struct<b:Int32>,"
  2655. " CONCURRENCY=3, BATCH_SIZE=1000000, CONNECTION='yc-folder34fse-con',"
  2656. " INIT=[0, 900]").IsOk());
  2657. UNIT_ASSERT(SqlToYql(
  2658. "PROCESS plato.Input"
  2659. " USING EXTERNAL FUNCTION('YANDEX-CLOUD', 'bar', TableRow())"
  2660. " WITH UNKNOWN_PARAM_1='837747712', UNKNOWN_PARAM_2=Tuple<Uint16, Utf8>,"
  2661. " INPUT_TYPE=Struct<a:Int32>, OUTPUT_TYPE=Struct<b:Int32>").IsOk());
  2662. }
  2663. Y_UNIT_TEST(InValidUseFunctions) {
  2664. ExpectFailWithError("PROCESS plato.Input USING some::udf(*) WITH INPUT_TYPE=Struct<a:Int32>",
  2665. "<main>:1:33: Error: PROCESS without USING EXTERNAL FUNCTION doesn't allow WITH block\n");
  2666. ExpectFailWithError("PROCESS plato.Input USING EXTERNAL FUNCTION('YANDEX-CLOUD', 'jhhjfh88134d')"
  2667. " WITH INPUT_TYPE=Struct<a:Int32>, OUTPUT_TYPE=Struct<b:Int32>"
  2668. " ASSUME ORDER BY key",
  2669. "<main>:1:129: Error: PROCESS with USING EXTERNAL FUNCTION doesn't allow ASSUME block\n");
  2670. ExpectFailWithError("PROCESS plato.Input USING EXTERNAL FUNCTION('YANDEX-CLOUD', 'foo', 'bar', 'baz')",
  2671. "<main>:1:15: Error: EXTERNAL FUNCTION requires from 2 to 3 arguments, but got: 4\n");
  2672. ExpectFailWithError("PROCESS plato.Input\n"
  2673. " USING EXTERNAL FUNCTION('YANDEX-CLOUD', 'foo', <|field_1: a1, field_b: b1|>)\n"
  2674. " WITH INPUT_TYPE=Struct<a:Int32>, OUTPUT_TYPE=Struct<b:Int32>,\n"
  2675. " CONCURRENCY=3, BATCH_SIZE=1000000, CONNECTION='yc-folder34fse-con',\n"
  2676. " CONCURRENCY=5, INPUT_TYPE=Struct<b:Bool>,\n"
  2677. " INIT=[0, 900]\n",
  2678. "<main>:5:2: Error: WITH \"CONCURRENCY\" clause should be specified only once\n"
  2679. "<main>:5:17: Error: WITH \"INPUT_TYPE\" clause should be specified only once\n");
  2680. }
  2681. }
  2682. Y_UNIT_TEST_SUITE(SqlToYQLErrors) {
  2683. Y_UNIT_TEST(UdfSyntaxSugarMissingCall) {
  2684. auto req = "SELECT Udf(DateTime::FromString, \"foo\" as RunConfig);";
  2685. auto res = SqlToYql(req);
  2686. TString a1 = Err2Str(res);
  2687. TString a2("<main>:1:8: Error: Abstract Udf Node can't be used as a part of expression.\n");
  2688. UNIT_ASSERT_NO_DIFF(a1, a2);
  2689. }
  2690. Y_UNIT_TEST(UdfSyntaxSugarIsNotCallable) {
  2691. auto req = "SELECT Udf(123, \"foo\" as RunConfig);";
  2692. auto res = SqlToYql(req);
  2693. TString a1 = Err2Str(res);
  2694. TString a2("<main>:1:8: Error: Udf: first argument must be a callable, like Foo::Bar\n");
  2695. UNIT_ASSERT_NO_DIFF(a1, a2);
  2696. }
  2697. Y_UNIT_TEST(UdfSyntaxSugarNoArgs) {
  2698. auto req = "SELECT Udf()();";
  2699. auto res = SqlToYql(req);
  2700. TString a1 = Err2Str(res);
  2701. TString a2("<main>:1:8: Error: Udf: expected at least one argument\n");
  2702. UNIT_ASSERT_NO_DIFF(a1, a2);
  2703. }
  2704. Y_UNIT_TEST(StrayUTF8) {
  2705. /// 'c' in plato is russian here
  2706. NYql::TAstParseResult res = SqlToYql("select * from сedar.Input");
  2707. UNIT_ASSERT(!res.Root);
  2708. TString a1 = Err2Str(res);
  2709. TString a2(R"foo(<main>:1:14: Error: token recognition error at: 'с'
  2710. )foo");
  2711. UNIT_ASSERT_NO_DIFF(a1, a2);
  2712. }
  2713. Y_UNIT_TEST(IvalidStringLiteralWithEscapedBackslash) {
  2714. NYql::TAstParseResult res1 = SqlToYql(R"foo($bar = 'a\\'b';)foo");
  2715. NYql::TAstParseResult res2 = SqlToYql(R"foo($bar = "a\\"b";)foo");
  2716. UNIT_ASSERT(!res1.Root);
  2717. UNIT_ASSERT(!res2.Root);
  2718. UNIT_ASSERT_NO_DIFF(Err2Str(res1), "<main>:1:13: Error: token recognition error at: '';'\n");
  2719. UNIT_ASSERT_NO_DIFF(Err2Str(res2), "<main>:1:13: Error: token recognition error at: '\";'\n");
  2720. }
  2721. Y_UNIT_TEST(InvalidHexInStringLiteral) {
  2722. NYql::TAstParseResult res = SqlToYql("select \"foo\\x1\\xfe\"");
  2723. UNIT_ASSERT(!res.Root);
  2724. TString a1 = Err2Str(res);
  2725. TString a2 = "<main>:1:15: Error: Failed to parse string literal: Invalid hexadecimal value\n";
  2726. UNIT_ASSERT_NO_DIFF(a1, a2);
  2727. }
  2728. Y_UNIT_TEST(InvalidOctalInMultilineStringLiteral) {
  2729. NYql::TAstParseResult res = SqlToYql("select \"foo\n"
  2730. "bar\n"
  2731. "\\01\"");
  2732. UNIT_ASSERT(!res.Root);
  2733. TString a1 = Err2Str(res);
  2734. TString a2 = "<main>:3:4: Error: Failed to parse string literal: Invalid octal value\n";
  2735. UNIT_ASSERT_NO_DIFF(a1, a2);
  2736. }
  2737. Y_UNIT_TEST(InvalidDoubleAtString) {
  2738. NYql::TAstParseResult res = SqlToYql("select @@@@@@");
  2739. UNIT_ASSERT(!res.Root);
  2740. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:12: Error: extraneous input '@' expecting {<EOF>, ';'}\n");
  2741. }
  2742. Y_UNIT_TEST(InvalidDoubleAtStringWhichWasAcceptedEarlier) {
  2743. NYql::TAstParseResult res = SqlToYql("SELECT @@foo@@ @ @@bar@@");
  2744. UNIT_ASSERT(!res.Root);
  2745. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:15: Error: mismatched input '@' expecting {<EOF>, ';'}\n");
  2746. }
  2747. Y_UNIT_TEST(InvalidStringFromTable) {
  2748. NYql::TAstParseResult res = SqlToYql("select \"FOO\"\"BAR from plato.foo");
  2749. UNIT_ASSERT(!res.Root);
  2750. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:12: Error: token recognition error at: '\"BAR from plato.foo'\n");
  2751. }
  2752. Y_UNIT_TEST(InvalidDoubleAtStringFromTable) {
  2753. NYql::TAstParseResult res = SqlToYql("select @@@@@@ from plato.foo");
  2754. UNIT_ASSERT(!res.Root);
  2755. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:12: Error: mismatched input '@' expecting {<EOF>, ';'}\n");
  2756. }
  2757. Y_UNIT_TEST(SelectInvalidSyntax) {
  2758. NYql::TAstParseResult res = SqlToYql("select 1 form Wat");
  2759. UNIT_ASSERT(!res.Root);
  2760. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:14: Error: extraneous input 'Wat' expecting {<EOF>, ';'}\n");
  2761. }
  2762. Y_UNIT_TEST(SelectNoCluster) {
  2763. NYql::TAstParseResult res = SqlToYql("select foo from bar");
  2764. UNIT_ASSERT(!res.Root);
  2765. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:1: Error: No cluster name given and no default cluster is selected\n");
  2766. }
  2767. Y_UNIT_TEST(SelectDuplicateColumns) {
  2768. NYql::TAstParseResult res = SqlToYql("select a, a from plato.Input");
  2769. UNIT_ASSERT(!res.Root);
  2770. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:11: Error: Unable to use duplicate column names. Collision in name: a\n");
  2771. }
  2772. Y_UNIT_TEST(SelectDuplicateLabels) {
  2773. NYql::TAstParseResult res = SqlToYql("select a as foo, b as foo from plato.Input");
  2774. UNIT_ASSERT(!res.Root);
  2775. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:18: Error: Unable to use duplicate column names. Collision in name: foo\n");
  2776. }
  2777. Y_UNIT_TEST(SelectCaseWithoutThen) {
  2778. NYql::TAstParseResult res = SqlToYql("select case when true 1;");
  2779. UNIT_ASSERT(!res.Root);
  2780. UNIT_ASSERT_NO_DIFF(Err2Str(res),
  2781. "<main>:1:22: Error: missing THEN at \'1\'\n"
  2782. "<main>:1:23: Error: extraneous input \';\' expecting {ELSE, END, WHEN}\n"
  2783. );
  2784. }
  2785. Y_UNIT_TEST(SelectComplexCaseWithoutThen) {
  2786. NYql::TAstParseResult res = SqlToYql(
  2787. "SELECT *\n"
  2788. "FROM plato.Input AS a\n"
  2789. "WHERE CASE WHEN a.key = \"foo\" a.subkey ELSE a.value END\n"
  2790. );
  2791. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:3:30: Error: missing THEN at 'a'\n");
  2792. }
  2793. Y_UNIT_TEST(SelectCaseWithoutEnd) {
  2794. NYql::TAstParseResult res = SqlToYql("select case a when b then c end from plato.Input");
  2795. UNIT_ASSERT(!res.Root);
  2796. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:8: Error: ELSE is required\n");
  2797. }
  2798. Y_UNIT_TEST(SelectWithBadAggregationNoInput) {
  2799. NYql::TAstParseResult res = SqlToYql("select a, Min(b), c");
  2800. UNIT_ASSERT(!res.Root);
  2801. UNIT_ASSERT_NO_DIFF(Err2Str(res),
  2802. "<main>:1:1: Error: Column references are not allowed without FROM\n"
  2803. "<main>:1:8: Error: Column reference 'a'\n"
  2804. "<main>:1:1: Error: Column references are not allowed without FROM\n"
  2805. "<main>:1:15: Error: Column reference 'b'\n"
  2806. "<main>:1:1: Error: Column references are not allowed without FROM\n"
  2807. "<main>:1:19: Error: Column reference 'c'\n"
  2808. );
  2809. }
  2810. Y_UNIT_TEST(SelectWithBadAggregation) {
  2811. ExpectFailWithError("select count(*), 1 + key from plato.Input",
  2812. "<main>:1:22: Error: Column `key` must either be a key column in GROUP BY or it should be used in aggregation function\n");
  2813. }
  2814. Y_UNIT_TEST(SelectWithBadAggregatedTerms) {
  2815. ExpectFailWithError("select key, 2 * subkey from plato.Input group by key",
  2816. "<main>:1:17: Error: Column `subkey` must either be a key column in GROUP BY or it should be used in aggregation function\n");
  2817. }
  2818. Y_UNIT_TEST(SelectDistinctWithBadAggregation) {
  2819. ExpectFailWithError("select distinct count(*), 1 + key from plato.Input",
  2820. "<main>:1:31: Error: Column `key` must either be a key column in GROUP BY or it should be used in aggregation function\n");
  2821. ExpectFailWithError("select distinct key, 2 * subkey from plato.Input group by key",
  2822. "<main>:1:26: Error: Column `subkey` must either be a key column in GROUP BY or it should be used in aggregation function\n");
  2823. }
  2824. Y_UNIT_TEST(SelectWithBadAggregationInHaving) {
  2825. ExpectFailWithError("select key from plato.Input group by key\n"
  2826. "having \"f\" || value == \"foo\"",
  2827. "<main>:2:15: Error: Column `value` must either be a key column in GROUP BY or it should be used in aggregation function\n");
  2828. }
  2829. Y_UNIT_TEST(JoinWithNonAggregatedColumnInProjection) {
  2830. ExpectFailWithError("select a.key, 1 + b.subkey\n"
  2831. "from plato.Input1 as a join plato.Input2 as b using(key)\n"
  2832. "group by a.key;",
  2833. "<main>:1:19: Error: Column `b.subkey` must either be a key column in GROUP BY or it should be used in aggregation function\n");
  2834. ExpectFailWithError("select a.key, 1 + b.subkey.x\n"
  2835. "from plato.Input1 as a join plato.Input2 as b using(key)\n"
  2836. "group by a.key;",
  2837. "<main>:1:19: Error: Column must either be a key column in GROUP BY or it should be used in aggregation function\n");
  2838. }
  2839. Y_UNIT_TEST(SelectWithBadAggregatedTermsWithSources) {
  2840. ExpectFailWithError("select key, 1 + a.subkey\n"
  2841. "from plato.Input1 as a\n"
  2842. "group by a.key;",
  2843. "<main>:1:17: Error: Column `a.subkey` must either be a key column in GROUP BY or it should be used in aggregation function\n");
  2844. ExpectFailWithError("select key, 1 + a.subkey.x\n"
  2845. "from plato.Input1 as a\n"
  2846. "group by a.key;",
  2847. "<main>:1:17: Error: Column must either be a key column in GROUP BY or it should be used in aggregation function\n");
  2848. }
  2849. Y_UNIT_TEST(WarnForAggregationBySelectAlias) {
  2850. NYql::TAstParseResult res = SqlToYql("select c + 1 as c from plato.Input\n"
  2851. "group by c");
  2852. UNIT_ASSERT(res.Root);
  2853. UNIT_ASSERT_NO_DIFF(Err2Str(res),
  2854. "<main>:2:11: Warning: GROUP BY will aggregate by column `c` instead of aggregating by SELECT expression with same alias, code: 4532\n"
  2855. "<main>:1:10: Warning: You should probably use alias in GROUP BY instead of using it here. Please consult documentation for more details, code: 4532\n");
  2856. res = SqlToYql("select c + 1 as c from plato.Input\n"
  2857. "group by Math::Floor(c + 2) as c;");
  2858. UNIT_ASSERT(res.Root);
  2859. UNIT_ASSERT_NO_DIFF(Err2Str(res),
  2860. "<main>:2:22: Warning: GROUP BY will aggregate by column `c` instead of aggregating by SELECT expression with same alias, code: 4532\n"
  2861. "<main>:1:10: Warning: You should probably use alias in GROUP BY instead of using it here. Please consult documentation for more details, code: 4532\n");
  2862. }
  2863. Y_UNIT_TEST(NoWarnForAggregationBySelectAliasWhenAggrFunctionsAreUsedInAlias) {
  2864. NYql::TAstParseResult res = SqlToYql("select\n"
  2865. " cast(avg(val) as int) as value,\n"
  2866. " value as key\n"
  2867. "from\n"
  2868. " plato.Input\n"
  2869. "group by value");
  2870. UNIT_ASSERT(res.Root);
  2871. UNIT_ASSERT(res.Issues.Size() == 0);
  2872. res = SqlToYql("select\n"
  2873. " cast(avg(val) over w as int) as value,\n"
  2874. " value as key\n"
  2875. "from\n"
  2876. " plato.Input\n"
  2877. "group by value\n"
  2878. "window w as ()");
  2879. UNIT_ASSERT(res.Root);
  2880. UNIT_ASSERT(res.Issues.Size() == 0);
  2881. }
  2882. Y_UNIT_TEST(NoWarnForAggregationBySelectAliasWhenQualifiedNameIsUsed) {
  2883. NYql::TAstParseResult res = SqlToYql("select\n"
  2884. " Unwrap(a.key) as key\n"
  2885. "from plato.Input as a\n"
  2886. "join plato.Input2 as b using(k)\n"
  2887. "group by a.key;");
  2888. UNIT_ASSERT(res.Root);
  2889. UNIT_ASSERT(res.Issues.Size() == 0);
  2890. res = SqlToYql("select Unwrap(a.key) as key\n"
  2891. "from plato.Input as a\n"
  2892. "group by a.key;");
  2893. UNIT_ASSERT(res.Root);
  2894. UNIT_ASSERT(res.Issues.Size() == 0);
  2895. }
  2896. Y_UNIT_TEST(NoWarnForAggregationBySelectAliasWhenTrivialRenamingIsUsed) {
  2897. NYql::TAstParseResult res = SqlToYql("select a.key as key\n"
  2898. "from plato.Input as a\n"
  2899. "group by key;");
  2900. UNIT_ASSERT(res.Root);
  2901. UNIT_ASSERT(res.Issues.Size() == 0);
  2902. res = SqlToYql("select key as key\n"
  2903. "from plato.Input\n"
  2904. "group by key;");
  2905. UNIT_ASSERT(res.Root);
  2906. UNIT_ASSERT(res.Issues.Size() == 0);
  2907. }
  2908. Y_UNIT_TEST(ErrorByAggregatingByExpressionWithSameExpressionInSelect) {
  2909. ExpectFailWithError("select k * 2 from plato.Input group by k * 2",
  2910. "<main>:1:8: Error: Column `k` must either be a key column in GROUP BY or it should be used in aggregation function\n");
  2911. }
  2912. Y_UNIT_TEST(ErrorForAggregationBySelectAlias) {
  2913. ExpectFailWithError("select key, Math::Floor(1.1 + a.subkey) as foo\n"
  2914. "from plato.Input as a\n"
  2915. "group by a.key, foo;",
  2916. "<main>:3:17: Warning: GROUP BY will aggregate by column `foo` instead of aggregating by SELECT expression with same alias, code: 4532\n"
  2917. "<main>:1:19: Warning: You should probably use alias in GROUP BY instead of using it here. Please consult documentation for more details, code: 4532\n"
  2918. "<main>:1:31: Error: Column `a.subkey` must either be a key column in GROUP BY or it should be used in aggregation function\n");
  2919. ExpectFailWithError("select c + 1 as c from plato.Input\n"
  2920. "group by Math::Floor(c + 2);",
  2921. "<main>:2:22: Warning: GROUP BY will aggregate by column `c` instead of aggregating by SELECT expression with same alias, code: 4532\n"
  2922. "<main>:1:10: Warning: You should probably use alias in GROUP BY instead of using it here. Please consult documentation for more details, code: 4532\n"
  2923. "<main>:1:8: Error: Column `c` must either be a key column in GROUP BY or it should be used in aggregation function\n");
  2924. }
  2925. Y_UNIT_TEST(ExplainQueryPlan) {
  2926. NYql::TAstParseResult res = SqlToYql("EXPLAIN Q U E R Y PLAN SELECT 1;");
  2927. UNIT_ASSERT(!res.Root);
  2928. UNIT_ASSERT_STRING_CONTAINS(Err2Str(res), "<main>:1:8: Error: mismatched input 'Q' expecting {");
  2929. }
  2930. Y_UNIT_TEST(SelectWithDuplicateGroupingColumns) {
  2931. NYql::TAstParseResult res = SqlToYql("select c from plato.Input group by c, c");
  2932. UNIT_ASSERT(!res.Root);
  2933. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:8: Error: Duplicate grouping column: c\n");
  2934. }
  2935. Y_UNIT_TEST(SelectWithBadAggregationInGrouping) {
  2936. NYql::TAstParseResult res = SqlToYql("select a, Min(b), c group by c");
  2937. UNIT_ASSERT(!res.Root);
  2938. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:1: Error: Column references are not allowed without FROM\n"
  2939. "<main>:1:30: Error: Column reference 'c'\n");
  2940. }
  2941. Y_UNIT_TEST(SelectWithOpOnBadAggregation) {
  2942. ExpectFailWithError("select 1 + a + Min(b) from plato.Input",
  2943. "<main>:1:12: Error: Column `a` must either be a key column in GROUP BY or it should be used in aggregation function\n");
  2944. }
  2945. Y_UNIT_TEST(SelectOrderByConstantNum) {
  2946. NYql::TAstParseResult res = SqlToYql("select a from plato.Input order by 1");
  2947. UNIT_ASSERT(!res.Root);
  2948. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:36: Error: Unable to ORDER BY constant expression\n");
  2949. }
  2950. Y_UNIT_TEST(SelectOrderByConstantExpr) {
  2951. NYql::TAstParseResult res = SqlToYql("select a from plato.Input order by 1 * 42");
  2952. UNIT_ASSERT(!res.Root);
  2953. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:38: Error: Unable to ORDER BY constant expression\n");
  2954. }
  2955. Y_UNIT_TEST(SelectOrderByConstantString) {
  2956. NYql::TAstParseResult res = SqlToYql("select a from plato.Input order by \"nest\"");
  2957. UNIT_ASSERT(!res.Root);
  2958. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:36: Error: Unable to ORDER BY constant expression\n");
  2959. }
  2960. Y_UNIT_TEST(SelectOrderByAggregated) {
  2961. NYql::TAstParseResult res = SqlToYql("select a from plato.Input order by min(a)");
  2962. UNIT_ASSERT(!res.Root);
  2963. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:36: Error: Unable to ORDER BY aggregated values\n");
  2964. }
  2965. Y_UNIT_TEST(ErrorInOrderByExpresison) {
  2966. NYql::TAstParseResult res = SqlToYql("select key, value from plato.Input order by (key as zey)");
  2967. UNIT_ASSERT(!res.Root);
  2968. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:45: Error: You should use in ORDER BY column name, qualified field, callable function or expression\n");
  2969. }
  2970. Y_UNIT_TEST(ErrorsInOrderByWhenColumnIsMissingInProjection) {
  2971. ExpectFailWithError("select subkey from (select 1 as subkey) order by key", "<main>:1:50: Error: Column key is not in source column set\n");
  2972. ExpectFailWithError("select subkey from plato.Input as a order by x.key", "<main>:1:46: Error: Unknown correlation name: x\n");
  2973. ExpectFailWithError("select distinct a, b from plato.Input order by c", "<main>:1:48: Error: Column c is not in source column set. Did you mean a?\n");
  2974. ExpectFailWithError("select count(*) as a from plato.Input order by c", "<main>:1:48: Error: Column c is not in source column set. Did you mean a?\n");
  2975. ExpectFailWithError("select count(*) as a, b, from plato.Input group by b order by c", "<main>:1:63: Error: Column c is not in source column set. Did you mean a?\n");
  2976. UNIT_ASSERT(SqlToYql("select a, b from plato.Input order by c").IsOk());
  2977. }
  2978. Y_UNIT_TEST(SelectAggregatedWhere) {
  2979. NYql::TAstParseResult res = SqlToYql("select * from plato.Input where count(key)");
  2980. UNIT_ASSERT(!res.Root);
  2981. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:33: Error: Can not use aggregated values in filtering\n");
  2982. }
  2983. Y_UNIT_TEST(DoubleFrom) {
  2984. NYql::TAstParseResult res = SqlToYql("from plato.Input select * from plato.Input");
  2985. UNIT_ASSERT(!res.Root);
  2986. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:27: Error: Only one FROM clause is allowed\n");
  2987. }
  2988. Y_UNIT_TEST(SelectJoinMissingCorrName) {
  2989. NYql::TAstParseResult res = SqlToYql("select * from plato.Input1 as a join plato.Input2 as b on a.key == key");
  2990. UNIT_ASSERT(!res.Root);
  2991. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:65: Error: JOIN: column requires correlation name\n");
  2992. }
  2993. Y_UNIT_TEST(SelectJoinMissingCorrName1) {
  2994. NYql::TAstParseResult res = SqlToYql(
  2995. "use plato;\n"
  2996. "$foo = select * from Input1;\n"
  2997. "select * from Input2 join $foo USING(key);\n"
  2998. );
  2999. UNIT_ASSERT(!res.Root);
  3000. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:3:27: Error: JOIN: missing correlation name for source\n");
  3001. }
  3002. Y_UNIT_TEST(SelectJoinMissingCorrName2) {
  3003. NYql::TAstParseResult res = SqlToYql(
  3004. "use plato;\n"
  3005. "$foo = select * from Input1;\n"
  3006. "select * from Input2 cross join $foo;\n"
  3007. );
  3008. UNIT_ASSERT(!res.Root);
  3009. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:3:33: Error: JOIN: missing correlation name for source\n");
  3010. }
  3011. Y_UNIT_TEST(SelectJoinEmptyCorrNames) {
  3012. NYql::TAstParseResult res = SqlToYql(
  3013. "$left = (SELECT * FROM plato.Input1 LIMIT 2);\n"
  3014. "$right = (SELECT * FROM plato.Input2 LIMIT 2);\n"
  3015. "SELECT * FROM $left FULL JOIN $right USING (key);\n"
  3016. );
  3017. UNIT_ASSERT(!res.Root);
  3018. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:3:45: Error: At least one correlation name is required in join\n");
  3019. }
  3020. Y_UNIT_TEST(SelectJoinSameCorrNames) {
  3021. NYql::TAstParseResult res = SqlToYql("SELECT Input.key FROM plato.Input JOIN plato.Input1 ON Input.key == Input.subkey\n");
  3022. UNIT_ASSERT(!res.Root);
  3023. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:66: Error: JOIN: different correlation names are required for joined tables\n");
  3024. }
  3025. Y_UNIT_TEST(SelectJoinConstPredicateArg) {
  3026. NYql::TAstParseResult res = SqlToYql("SELECT * FROM plato.Input1 as A JOIN plato.Input2 as B ON A.key == B.key AND A.subkey == \"wtf\"\n");
  3027. UNIT_ASSERT(!res.Root);
  3028. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:87: Error: JOIN: each equality predicate argument must depend on exactly one JOIN input\n");
  3029. }
  3030. Y_UNIT_TEST(SelectJoinNonEqualityPredicate) {
  3031. NYql::TAstParseResult res = SqlToYql("SELECT * FROM plato.Input1 as A JOIN plato.Input2 as B ON A.key == B.key AND A.subkey > B.subkey\n");
  3032. UNIT_ASSERT(!res.Root);
  3033. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:87: Error: JOIN ON expression must be a conjunction of equality predicates\n");
  3034. }
  3035. Y_UNIT_TEST(SelectEquiJoinCorrNameOutOfScope) {
  3036. NYql::TAstParseResult res = SqlToYql(
  3037. "PRAGMA equijoin;\n"
  3038. "SELECT * FROM plato.A JOIN plato.B ON A.key == C.key JOIN plato.C ON A.subkey == C.subkey;\n"
  3039. );
  3040. UNIT_ASSERT(!res.Root);
  3041. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:2:45: Error: JOIN: can not use source: C in equality predicate, it is out of current join scope\n");
  3042. }
  3043. Y_UNIT_TEST(SelectEquiJoinNoRightSource) {
  3044. NYql::TAstParseResult res = SqlToYql(
  3045. "PRAGMA equijoin;\n"
  3046. "SELECT * FROM plato.A JOIN plato.B ON A.key == B.key JOIN plato.C ON A.subkey == B.subkey;\n"
  3047. );
  3048. UNIT_ASSERT(!res.Root);
  3049. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:2:79: Error: JOIN ON equality predicate must have one of its arguments from the rightmost source\n");
  3050. }
  3051. Y_UNIT_TEST(SelectEquiJoinOuterWithoutType) {
  3052. NYql::TAstParseResult res = SqlToYql(
  3053. "SELECT * FROM plato.A Outer JOIN plato.B ON A.key == B.key;\n"
  3054. );
  3055. UNIT_ASSERT(!res.Root);
  3056. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:23: Error: Invalid join type: OUTER JOIN. OUTER keyword is optional and can only be used after LEFT, RIGHT or FULL\n");
  3057. }
  3058. Y_UNIT_TEST(SelectEquiJoinOuterWithWrongType) {
  3059. NYql::TAstParseResult res = SqlToYql(
  3060. "SELECT * FROM plato.A LEFT semi OUTER JOIN plato.B ON A.key == B.key;\n"
  3061. );
  3062. UNIT_ASSERT(!res.Root);
  3063. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:33: Error: Invalid join type: LEFT SEMI OUTER JOIN. OUTER keyword is optional and can only be used after LEFT, RIGHT or FULL\n");
  3064. }
  3065. Y_UNIT_TEST(InsertNoCluster) {
  3066. NYql::TAstParseResult res = SqlToYql("insert into Output (foo) values (1)");
  3067. UNIT_ASSERT(!res.Root);
  3068. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:1: Error: No cluster name given and no default cluster is selected\n");
  3069. }
  3070. Y_UNIT_TEST(InsertValuesNoLabels) {
  3071. NYql::TAstParseResult res = SqlToYql("insert into plato.Output values (1)");
  3072. UNIT_ASSERT(!res.Root);
  3073. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:19: Error: INSERT INTO ... VALUES requires specification of table columns\n");
  3074. }
  3075. Y_UNIT_TEST(UpsertValuesNoLabelsKikimr) {
  3076. NYql::TAstParseResult res = SqlToYql("upsert into plato.Output values (1)", 10, TString(NYql::KikimrProviderName));
  3077. UNIT_ASSERT(!res.Root);
  3078. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:19: Error: UPSERT INTO ... VALUES requires specification of table columns\n");
  3079. }
  3080. Y_UNIT_TEST(ReplaceValuesNoLabelsKikimr) {
  3081. NYql::TAstParseResult res = SqlToYql("replace into plato.Output values (1)", 10, TString(NYql::KikimrProviderName));
  3082. UNIT_ASSERT(!res.Root);
  3083. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:20: Error: REPLACE INTO ... VALUES requires specification of table columns\n");
  3084. }
  3085. Y_UNIT_TEST(InsertValuesInvalidLabels) {
  3086. NYql::TAstParseResult res = SqlToYql("insert into plato.Output (foo) values (1, 2)");
  3087. UNIT_ASSERT(!res.Root);
  3088. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:27: Error: VALUES have 2 columns, INSERT INTO expects: 1\n");
  3089. }
  3090. Y_UNIT_TEST(BuiltinFileOpNoArgs) {
  3091. NYql::TAstParseResult res = SqlToYql("select FilePath()");
  3092. UNIT_ASSERT(!res.Root);
  3093. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:8: Error: FilePath() requires exactly 1 arguments, given: 0\n");
  3094. }
  3095. Y_UNIT_TEST(ProcessWithHaving) {
  3096. NYql::TAstParseResult res = SqlToYql("process plato.Input using some::udf(value) having value == 1");
  3097. UNIT_ASSERT(!res.Root);
  3098. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:15: Error: PROCESS does not allow HAVING yet! You may request it on yql@ maillist.\n");
  3099. }
  3100. Y_UNIT_TEST(ReduceNoBy) {
  3101. NYql::TAstParseResult res = SqlToYql("reduce plato.Input using some::udf(value)");
  3102. UNIT_ASSERT(!res.Root);
  3103. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:19: Error: mismatched input 'using' expecting {',', ON, PRESORT}\n");
  3104. }
  3105. Y_UNIT_TEST(ReduceDistinct) {
  3106. NYql::TAstParseResult res = SqlToYql("reduce plato.Input on key using some::udf(distinct value)");
  3107. UNIT_ASSERT(!res.Root);
  3108. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:43: Error: DISTINCT can not be used in PROCESS/REDUCE\n");
  3109. }
  3110. Y_UNIT_TEST(CreateTableWithView) {
  3111. NYql::TAstParseResult res = SqlToYql("CREATE TABLE plato.foo:bar (key INT);");
  3112. UNIT_ASSERT(!res.Root);
  3113. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:22: Error: mismatched input ':' expecting '('\n");
  3114. }
  3115. Y_UNIT_TEST(AsteriskWithSomethingAfter) {
  3116. NYql::TAstParseResult res = SqlToYql("select *, LENGTH(value) from plato.Input;");
  3117. UNIT_ASSERT(!res.Root);
  3118. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:8: Error: Unable to use plain '*' with other projection items. Please use qualified asterisk instead: '<table>.*' (<table> can be either table name or table alias).\n");
  3119. }
  3120. Y_UNIT_TEST(AsteriskWithSomethingBefore) {
  3121. NYql::TAstParseResult res = SqlToYql("select LENGTH(value), * from plato.Input;");
  3122. UNIT_ASSERT(!res.Root);
  3123. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:23: Error: Unable to use plain '*' with other projection items. Please use qualified asterisk instead: '<table>.*' (<table> can be either table name or table alias).\n");
  3124. }
  3125. Y_UNIT_TEST(DuplicatedQualifiedAsterisk) {
  3126. NYql::TAstParseResult res = SqlToYql("select in.*, key, in.* from plato.Input as in;");
  3127. UNIT_ASSERT(!res.Root);
  3128. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:19: Error: Unable to use twice same quialified asterisk. Invalid source: in\n");
  3129. }
  3130. Y_UNIT_TEST(BrokenLabel) {
  3131. NYql::TAstParseResult res = SqlToYql("select in.*, key as `funny.label` from plato.Input as in;");
  3132. UNIT_ASSERT(!res.Root);
  3133. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:14: Error: Unable to use '.' in column name. Invalid column name: funny.label\n");
  3134. }
  3135. Y_UNIT_TEST(KeyConflictDetect0) {
  3136. NYql::TAstParseResult res = SqlToYql("select key, in.key as key from plato.Input as in;");
  3137. UNIT_ASSERT(!res.Root);
  3138. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:13: Error: Unable to use duplicate column names. Collision in name: key\n");
  3139. }
  3140. Y_UNIT_TEST(KeyConflictDetect1) {
  3141. NYql::TAstParseResult res = SqlToYql("select length(key) as key, key from plato.Input;");
  3142. UNIT_ASSERT(!res.Root);
  3143. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:28: Error: Unable to use duplicate column names. Collision in name: key\n");
  3144. }
  3145. Y_UNIT_TEST(KeyConflictDetect2) {
  3146. NYql::TAstParseResult res = SqlToYql("select key, in.key from plato.Input as in;");
  3147. UNIT_ASSERT(!res.Root);
  3148. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:1: Error: Duplicate column: key\n");
  3149. }
  3150. Y_UNIT_TEST(AutogenerationAliasWithCollisionConflict1) {
  3151. UNIT_ASSERT(SqlToYql("select LENGTH(Value), key as column0 from plato.Input;").IsOk());
  3152. }
  3153. Y_UNIT_TEST(AutogenerationAliasWithCollisionConflict2) {
  3154. UNIT_ASSERT(SqlToYql("select key as column1, LENGTH(Value) from plato.Input;").IsOk());
  3155. }
  3156. Y_UNIT_TEST(MissedSourceTableForQualifiedAsteriskOnSimpleSelect) {
  3157. NYql::TAstParseResult res = SqlToYql("use plato; select Intop.*, Input.key from plato.Input;");
  3158. UNIT_ASSERT(!res.Root);
  3159. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:19: Error: Unknown correlation name: Intop\n");
  3160. }
  3161. Y_UNIT_TEST(MissedSourceTableForQualifiedAsteriskOnJoin) {
  3162. NYql::TAstParseResult res = SqlToYql("use plato; select tmissed.*, t2.*, t1.key from plato.Input as t1 join plato.Input as t2 on t1.key==t2.key;");
  3163. UNIT_ASSERT(!res.Root);
  3164. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:19: Error: Unknown correlation name for asterisk: tmissed\n");
  3165. }
  3166. Y_UNIT_TEST(UnableToReferenceOnNotExistSubcolumn) {
  3167. NYql::TAstParseResult res = SqlToYql("select b.subkey from (select key from plato.Input as a) as b;");
  3168. UNIT_ASSERT(!res.Root);
  3169. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:8: Error: Column subkey is not in source column set\n");
  3170. }
  3171. Y_UNIT_TEST(ConflictOnSameNameWithQualify0) {
  3172. NYql::TAstParseResult res = SqlToYql("select in.key, in.key as key from plato.Input as in;");
  3173. UNIT_ASSERT(!res.Root);
  3174. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:1: Error: Duplicate column: key\n");
  3175. }
  3176. Y_UNIT_TEST(ConflictOnSameNameWithQualify1) {
  3177. NYql::TAstParseResult res = SqlToYql("select in.key, length(key) as key from plato.Input as in;");
  3178. UNIT_ASSERT(!res.Root);
  3179. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:1: Error: Duplicate column: key\n");
  3180. }
  3181. Y_UNIT_TEST(ConflictOnSameNameWithQualify2) {
  3182. NYql::TAstParseResult res = SqlToYql("select key, in.key from plato.Input as in;");
  3183. UNIT_ASSERT(!res.Root);
  3184. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:1: Error: Duplicate column: key\n");
  3185. }
  3186. Y_UNIT_TEST(ConflictOnSameNameWithQualify3) {
  3187. NYql::TAstParseResult res = SqlToYql("select in.key, subkey as key from plato.Input as in;");
  3188. UNIT_ASSERT(!res.Root);
  3189. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:1: Error: Duplicate column: key\n");
  3190. }
  3191. Y_UNIT_TEST(SelectFlattenBySameColumns) {
  3192. NYql::TAstParseResult res = SqlToYql("select key from plato.Input flatten by (key, key as kk)");
  3193. UNIT_ASSERT(!res.Root);
  3194. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:46: Error: Duplicate column name found: key in FlattenBy section\n");
  3195. }
  3196. Y_UNIT_TEST(SelectFlattenBySameAliases) {
  3197. NYql::TAstParseResult res = SqlToYql("select key from plato.Input flatten by (key as kk, subkey as kk);");
  3198. UNIT_ASSERT(!res.Root);
  3199. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:52: Error: Duplicate alias found: kk in FlattenBy section\n");
  3200. }
  3201. Y_UNIT_TEST(SelectFlattenByExprSameAliases) {
  3202. NYql::TAstParseResult res = SqlToYql("select key from plato.Input flatten by (key as kk, ListSkip(subkey,1) as kk);");
  3203. UNIT_ASSERT(!res.Root);
  3204. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:52: Error: Collision between alias and column name: kk in FlattenBy section\n");
  3205. }
  3206. Y_UNIT_TEST(SelectFlattenByConflictNameAndAlias0) {
  3207. NYql::TAstParseResult res = SqlToYql("select key from plato.Input flatten by (key, subkey as key);");
  3208. UNIT_ASSERT(!res.Root);
  3209. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:46: Error: Collision between alias and column name: key in FlattenBy section\n");
  3210. }
  3211. Y_UNIT_TEST(SelectFlattenByConflictNameAndAlias1) {
  3212. NYql::TAstParseResult res = SqlToYql("select key from plato.Input flatten by (key as kk, subkey as key);");
  3213. UNIT_ASSERT(!res.Root);
  3214. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:52: Error: Collision between alias and column name: key in FlattenBy section\n");
  3215. }
  3216. Y_UNIT_TEST(SelectFlattenByExprConflictNameAndAlias1) {
  3217. NYql::TAstParseResult res = SqlToYql("select key from plato.Input flatten by (key as kk, ListSkip(subkey,1) as key);");
  3218. UNIT_ASSERT(!res.Root);
  3219. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:52: Error: Duplicate column name found: key in FlattenBy section\n");
  3220. }
  3221. Y_UNIT_TEST(SelectFlattenByUnnamedExpr) {
  3222. NYql::TAstParseResult res = SqlToYql("select key from plato.Input flatten by (key, ListSkip(key, 1))");
  3223. UNIT_ASSERT(!res.Root);
  3224. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:46: Error: Unnamed expression after FLATTEN BY is not allowed\n");
  3225. }
  3226. Y_UNIT_TEST(UseInOnStrings) {
  3227. NYql::TAstParseResult res = SqlToYql("select * from plato.Input where \"foo\" in \"foovalue\";");
  3228. UNIT_ASSERT(!res.Root);
  3229. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:42: Error: Unable to use IN predicate with string argument, it won't search substring - "
  3230. "expecting tuple, list, dict or single column table source\n");
  3231. }
  3232. Y_UNIT_TEST(UseSubqueryInScalarContextInsideIn) {
  3233. NYql::TAstParseResult res = SqlToYql("$q = (select key from plato.Input); select * from plato.Input where subkey in ($q);");
  3234. UNIT_ASSERT(res.Root);
  3235. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:79: Warning: Using subrequest in scalar context after IN, "
  3236. "perhaps you should remove parenthesis here, code: 4501\n");
  3237. }
  3238. Y_UNIT_TEST(InHintsWithKeywordClash) {
  3239. NYql::TAstParseResult res = SqlToYql("SELECT COMPACT FROM plato.Input WHERE COMPACT IN COMPACT `COMPACT`(1,2,3)");
  3240. UNIT_ASSERT(!res.Root);
  3241. // should try to parse last compact as call expression
  3242. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:58: Error: Unknown builtin: COMPACT\n");
  3243. }
  3244. Y_UNIT_TEST(ErrorColumnPosition) {
  3245. NYql::TAstParseResult res = SqlToYql(
  3246. "USE plato;\n"
  3247. "SELECT \n"
  3248. "value FROM (\n"
  3249. "select key from Input\n"
  3250. ");\n"
  3251. );
  3252. UNIT_ASSERT(!res.Root);
  3253. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:3:1: Error: Column value is not in source column set\n");
  3254. }
  3255. Y_UNIT_TEST(PrimaryViewAbortMapReduce) {
  3256. NYql::TAstParseResult res = SqlToYql("SELECT key FROM plato.Input VIEW PRIMARY KEY");
  3257. UNIT_ASSERT(!res.Root);
  3258. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:17: Error: primary view is not supported for yt tables\n");
  3259. }
  3260. Y_UNIT_TEST(InsertAbortMapReduce) {
  3261. NYql::TAstParseResult res = SqlToYql("INSERT OR ABORT INTO plato.Output SELECT key FROM plato.Input");
  3262. UNIT_ASSERT(!res.Root);
  3263. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:0: Error: INSERT OR ABORT INTO is not supported for yt tables\n");
  3264. }
  3265. Y_UNIT_TEST(ReplaceIntoMapReduce) {
  3266. NYql::TAstParseResult res = SqlToYql("REPLACE INTO plato.Output SELECT key FROM plato.Input");
  3267. UNIT_ASSERT(!res.Root);
  3268. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:0: Error: Meaning of REPLACE INTO has been changed, now you should use INSERT INTO <table> WITH TRUNCATE ... for yt\n");
  3269. }
  3270. Y_UNIT_TEST(UpsertIntoMapReduce) {
  3271. NYql::TAstParseResult res = SqlToYql("UPSERT INTO plato.Output SELECT key FROM plato.Input");
  3272. UNIT_ASSERT(!res.Root);
  3273. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:0: Error: UPSERT INTO is not supported for yt tables\n");
  3274. }
  3275. Y_UNIT_TEST(UpdateMapReduce) {
  3276. NYql::TAstParseResult res = SqlToYql("UPDATE plato.Output SET value = value + 1 WHERE key < 1");
  3277. UNIT_ASSERT(!res.Root);
  3278. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:0: Error: UPDATE is unsupported for yt\n");
  3279. }
  3280. Y_UNIT_TEST(DeleteMapReduce) {
  3281. NYql::TAstParseResult res = SqlToYql("DELETE FROM plato.Output WHERE key < 1");
  3282. UNIT_ASSERT(!res.Root);
  3283. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:0: Error: DELETE is unsupported for yt\n");
  3284. }
  3285. Y_UNIT_TEST(ReplaceIntoWithTruncate) {
  3286. NYql::TAstParseResult res = SqlToYql("REPLACE INTO plato.Output WITH TRUNCATE SELECT key FROM plato.Input");
  3287. UNIT_ASSERT(!res.Root);
  3288. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:32: Error: Unable REPLACE INTO with truncate mode\n");
  3289. }
  3290. Y_UNIT_TEST(UpsertIntoWithTruncate) {
  3291. NYql::TAstParseResult res = SqlToYql("UPSERT INTO plato.Output WITH TRUNCATE SELECT key FROM plato.Input");
  3292. UNIT_ASSERT(!res.Root);
  3293. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:31: Error: Unable UPSERT INTO with truncate mode\n");
  3294. }
  3295. Y_UNIT_TEST(InsertIntoWithTruncateKikimr) {
  3296. NYql::TAstParseResult res = SqlToYql("INSERT INTO plato.Output WITH TRUNCATE SELECT key FROM plato.Input", 10, TString(NYql::KikimrProviderName));
  3297. UNIT_ASSERT(!res.Root);
  3298. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:0: Error: INSERT INTO WITH TRUNCATE is not supported for kikimr tables\n");
  3299. }
  3300. Y_UNIT_TEST(InsertIntoWithWrongArgumentCount) {
  3301. NYql::TAstParseResult res = SqlToYql("insert into plato.Output with truncate (key, value, subkey) values (5, '1', '2', '3');");
  3302. UNIT_ASSERT(!res.Root);
  3303. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:53: Error: VALUES have 4 columns, INSERT INTO ... WITH TRUNCATE expects: 3\n");
  3304. }
  3305. Y_UNIT_TEST(UpsertWithWrongArgumentCount) {
  3306. NYql::TAstParseResult res = SqlToYql("upsert into plato.Output (key, value, subkey) values (2, '3');", 10, TString(NYql::KikimrProviderName));
  3307. UNIT_ASSERT(!res.Root);
  3308. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:39: Error: VALUES have 2 columns, UPSERT INTO expects: 3\n");
  3309. }
  3310. Y_UNIT_TEST(GroupingSetByExprWithoutAlias) {
  3311. NYql::TAstParseResult res = SqlToYql("SELECT key FROM plato.Input GROUP BY GROUPING SETS (cast(key as uint32), subkey);");
  3312. UNIT_ASSERT(!res.Root);
  3313. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:53: Error: Unnamed expressions are not supported in GROUPING SETS. Please use '<expr> AS <name>'.\n");
  3314. }
  3315. Y_UNIT_TEST(GroupingSetByExprWithoutAlias2) {
  3316. NYql::TAstParseResult res = SqlToYql("SELECT key FROM plato.Input GROUP BY subkey || subkey, GROUPING SETS (\n"
  3317. "cast(key as uint32), subkey);");
  3318. UNIT_ASSERT(!res.Root);
  3319. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:2:1: Error: Unnamed expressions are not supported in GROUPING SETS. Please use '<expr> AS <name>'.\n");
  3320. }
  3321. Y_UNIT_TEST(CubeByExprWithoutAlias) {
  3322. NYql::TAstParseResult res = SqlToYql("SELECT key FROM plato.Input GROUP BY CUBE (key, subkey / key);");
  3323. UNIT_ASSERT(!res.Root);
  3324. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:56: Error: Unnamed expressions are not supported in CUBE. Please use '<expr> AS <name>'.\n");
  3325. }
  3326. Y_UNIT_TEST(RollupByExprWithoutAlias) {
  3327. NYql::TAstParseResult res = SqlToYql("SELECT key FROM plato.Input GROUP BY ROLLUP (subkey / key);");
  3328. UNIT_ASSERT(!res.Root);
  3329. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:53: Error: Unnamed expressions are not supported in ROLLUP. Please use '<expr> AS <name>'.\n");
  3330. }
  3331. Y_UNIT_TEST(GroupByHugeCubeDeniedNoPragma) {
  3332. NYql::TAstParseResult res = SqlToYql("SELECT key FROM plato.Input GROUP BY CUBE (key, subkey, value, key + subkey as sum, key - subkey as sub, key + val as keyval);");
  3333. UNIT_ASSERT(!res.Root);
  3334. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:119: Error: GROUP BY CUBE is allowed only for 5 columns, but you use 6\n");
  3335. }
  3336. Y_UNIT_TEST(GroupByInvalidPragma) {
  3337. NYql::TAstParseResult res = SqlToYql("PRAGMA GroupByCubeLimit = '-4';");
  3338. UNIT_ASSERT(!res.Root);
  3339. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:27: Error: Expected unsigned integer literal as a single argument for: GroupByCubeLimit\n");
  3340. }
  3341. Y_UNIT_TEST(GroupByHugeCubeDeniedPragme) {
  3342. NYql::TAstParseResult res = SqlToYql("PRAGMA GroupByCubeLimit = '4'; SELECT key FROM plato.Input GROUP BY CUBE (key, subkey, value, key + subkey as sum, key - subkey as sub);");
  3343. UNIT_ASSERT(!res.Root);
  3344. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:132: Error: GROUP BY CUBE is allowed only for 4 columns, but you use 5\n");
  3345. }
  3346. Y_UNIT_TEST(GroupByFewBigCubes) {
  3347. NYql::TAstParseResult res = SqlToYql("SELECT key FROM plato.Input GROUP BY CUBE(key, subkey, key + subkey as sum), CUBE(value, value + key + subkey as total);");
  3348. UNIT_ASSERT(!res.Root);
  3349. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:1: Error: Unable to GROUP BY more than 64 groups, you try use 80 groups\n");
  3350. }
  3351. Y_UNIT_TEST(GroupByFewBigCubesWithPragmaLimit) {
  3352. NYql::TAstParseResult res = SqlToYql("PRAGMA GroupByLimit = '16'; SELECT key FROM plato.Input GROUP BY GROUPING SETS(key, subkey, key + subkey as sum), ROLLUP(value, value + key + subkey as total);");
  3353. UNIT_ASSERT(!res.Root);
  3354. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:29: Error: Unable to GROUP BY more than 16 groups, you try use 18 groups\n");
  3355. }
  3356. Y_UNIT_TEST(NoGroupingColumn0) {
  3357. NYql::TAstParseResult res = SqlToYql(
  3358. "select count(1), key_first, val_first, grouping(key_first, val_first, nomind) as group\n"
  3359. "from plato.Input group by grouping sets (cast(key as uint32) /100 as key_first, Substring(value, 1, 1) as val_first);");
  3360. UNIT_ASSERT(!res.Root);
  3361. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:71: Error: Column 'nomind' is not a grouping column\n");
  3362. }
  3363. Y_UNIT_TEST(NoGroupingColumn1) {
  3364. NYql::TAstParseResult res = SqlToYql("select count(1), grouping(key, value) as group_duo from plato.Input group by cube (key, subkey);");
  3365. UNIT_ASSERT(!res.Root);
  3366. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:32: Error: Column 'value' is not a grouping column\n");
  3367. }
  3368. Y_UNIT_TEST(EmptyAccess0) {
  3369. NYql::TAstParseResult res = SqlToYql("insert into plato.Output (list0, list1) values (AsList(0, 1, 2), AsList(``));");
  3370. UNIT_ASSERT(!res.Root);
  3371. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:73: Error: Column reference \"\" is not allowed in current scope\n");
  3372. }
  3373. Y_UNIT_TEST(EmptyAccess1) {
  3374. NYql::TAstParseResult res = SqlToYql("insert into plato.Output (list0, list1) values (AsList(0, 1, 2), ``);");
  3375. UNIT_ASSERT(!res.Root);
  3376. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:66: Error: Column reference \"\" is not allowed in current scope\n");
  3377. }
  3378. Y_UNIT_TEST(UseUnknownColumnInInsert) {
  3379. NYql::TAstParseResult res = SqlToYql("insert into plato.Output (list0, list1) values (AsList(0, 1, 2), AsList(`test`));");
  3380. UNIT_ASSERT(!res.Root);
  3381. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:73: Error: Column reference \"test\" is not allowed in current scope\n");
  3382. }
  3383. Y_UNIT_TEST(GroupByEmptyColumn) {
  3384. NYql::TAstParseResult res = SqlToYql("select count(1) from plato.Input group by ``;");
  3385. UNIT_ASSERT(!res.Root);
  3386. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:43: Error: Column name can not be empty\n");
  3387. }
  3388. Y_UNIT_TEST(ConvertNumberOutOfBase) {
  3389. NYql::TAstParseResult res = SqlToYql("select 0o80l;");
  3390. UNIT_ASSERT(!res.Root);
  3391. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:8: Error: Failed to parse number from string: 0o80l, char: '8' is out of base: 8\n");
  3392. }
  3393. Y_UNIT_TEST(ConvertNumberOutOfRangeForInt64ButFitsInUint64) {
  3394. NYql::TAstParseResult res = SqlToYql("select 0xc000000000000000l;");
  3395. UNIT_ASSERT(!res.Root);
  3396. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:8: Error: Failed to parse 13835058055282163712 as integer literal of Int64 type: value out of range for Int64\n");
  3397. }
  3398. Y_UNIT_TEST(ConvertNumberOutOfRangeUint64) {
  3399. NYql::TAstParseResult res = SqlToYql("select 0xc0000000000000000l;");
  3400. UNIT_ASSERT(!res.Root);
  3401. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:8: Error: Failed to parse number from string: 0xc0000000000000000l, number limit overflow\n");
  3402. res = SqlToYql("select 1234234543563435151456;\n");
  3403. UNIT_ASSERT(!res.Root);
  3404. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:8: Error: Failed to parse number from string: 1234234543563435151456, number limit overflow\n");
  3405. }
  3406. Y_UNIT_TEST(ConvertNumberNegativeOutOfRange) {
  3407. NYql::TAstParseResult res = SqlToYql("select -9223372036854775808;\n"
  3408. "select -9223372036854775809;");
  3409. UNIT_ASSERT(!res.Root);
  3410. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:2:8: Error: Failed to parse negative integer: -9223372036854775809, number limit overflow\n");
  3411. }
  3412. Y_UNIT_TEST(InvaildUsageReal0) {
  3413. NYql::TAstParseResult res = SqlToYql("select .0;");
  3414. UNIT_ASSERT(!res.Root);
  3415. UNIT_ASSERT_STRING_CONTAINS(Err2Str(res), "<main>:1:7: Error: extraneous input '.' expecting {");
  3416. }
  3417. Y_UNIT_TEST(InvaildUsageReal1) {
  3418. NYql::TAstParseResult res = SqlToYql("select .0f;");
  3419. UNIT_ASSERT(!res.Root);
  3420. UNIT_ASSERT_STRING_CONTAINS(Err2Str(res), "<main>:1:7: Error: extraneous input '.' expecting {");
  3421. }
  3422. Y_UNIT_TEST(InvaildUsageWinFunctionWithoutWindow) {
  3423. NYql::TAstParseResult res = SqlToYql("select lead(key, 2) from plato.Input;");
  3424. UNIT_ASSERT(!res.Root);
  3425. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:8: Error: Failed to use window function Lead without window specification\n");
  3426. }
  3427. Y_UNIT_TEST(DropTableWithIfExists) {
  3428. NYql::TAstParseResult res = SqlToYql("DROP TABLE IF EXISTS plato.foo;");
  3429. UNIT_ASSERT(res.Root);
  3430. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  3431. if (word == "Write") {
  3432. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("drop_if_exists"));
  3433. }
  3434. };
  3435. TWordCountHive elementStat = { {TString("Write"), 0}};
  3436. VerifyProgram(res, elementStat, verifyLine);
  3437. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  3438. }
  3439. Y_UNIT_TEST(TooManyErrors) {
  3440. const char* q = R"(
  3441. USE plato;
  3442. select A, B, C, D, E, F, G, H, I, J, K, L, M, N from (select b from `abc`);
  3443. )";
  3444. NYql::TAstParseResult res = SqlToYql(q, 10);
  3445. UNIT_ASSERT(!res.Root);
  3446. UNIT_ASSERT_NO_DIFF(Err2Str(res),
  3447. R"(<main>:3:16: Error: Column A is not in source column set. Did you mean b?
  3448. <main>:3:19: Error: Column B is not in source column set. Did you mean b?
  3449. <main>:3:22: Error: Column C is not in source column set. Did you mean b?
  3450. <main>:3:25: Error: Column D is not in source column set. Did you mean b?
  3451. <main>:3:28: Error: Column E is not in source column set. Did you mean b?
  3452. <main>:3:31: Error: Column F is not in source column set. Did you mean b?
  3453. <main>:3:34: Error: Column G is not in source column set. Did you mean b?
  3454. <main>:3:37: Error: Column H is not in source column set. Did you mean b?
  3455. <main>:3:40: Error: Column I is not in source column set. Did you mean b?
  3456. <main>: Error: Too many issues, code: 1
  3457. )");
  3458. };
  3459. Y_UNIT_TEST(ShouldCloneBindingForNamedParameter) {
  3460. NYql::TAstParseResult res = SqlToYql(R"($f = () -> {
  3461. $value_type = TypeOf(1);
  3462. $pair_type = StructType(
  3463. TypeOf("2") AS key,
  3464. $value_type AS value
  3465. );
  3466. RETURN TupleType(
  3467. ListType($value_type),
  3468. $pair_type);
  3469. };
  3470. select FormatType($f());
  3471. )");
  3472. UNIT_ASSERT(res.Root);
  3473. }
  3474. Y_UNIT_TEST(BlockedInvalidFrameBounds) {
  3475. auto check = [](const TString& frame, const TString& err) {
  3476. const TString prefix = "SELECT SUM(x) OVER w FROM plato.Input WINDOW w AS (PARTITION BY key ORDER BY subkey\n";
  3477. NYql::TAstParseResult res = SqlToYql(prefix + frame + ")");
  3478. UNIT_ASSERT(!res.Root);
  3479. UNIT_ASSERT_NO_DIFF(Err2Str(res), err);
  3480. };
  3481. check("ROWS UNBOUNDED FOLLOWING", "<main>:2:5: Error: Frame cannot start from UNBOUNDED FOLLOWING\n");
  3482. check("ROWS BETWEEN 5 PRECEDING AND UNBOUNDED PRECEDING", "<main>:2:29: Error: Frame cannot end with UNBOUNDED PRECEDING\n");
  3483. check("ROWS BETWEEN CURRENT ROW AND 5 PRECEDING", "<main>:2:13: Error: Frame cannot start from CURRENT ROW and end with PRECEDING\n");
  3484. check("ROWS BETWEEN 5 FOLLOWING AND CURRENT ROW", "<main>:2:14: Error: Frame cannot start from FOLLOWING and end with CURRENT ROW\n");
  3485. check("ROWS BETWEEN 5 FOLLOWING AND 5 PRECEDING", "<main>:2:14: Error: Frame cannot start from FOLLOWING and end with PRECEDING\n");
  3486. }
  3487. Y_UNIT_TEST(BlockedRangeValueWithoutSingleOrderBy) {
  3488. UNIT_ASSERT(SqlToYql("SELECT COUNT(*) OVER (RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) FROM plato.Input").IsOk());
  3489. UNIT_ASSERT(SqlToYql("SELECT COUNT(*) OVER (RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) FROM plato.Input").IsOk());
  3490. auto res = SqlToYql("SELECT COUNT(*) OVER (RANGE 5 PRECEDING) FROM plato.Input");
  3491. UNIT_ASSERT(!res.Root);
  3492. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:29: Error: RANGE with <offset> PRECEDING/FOLLOWING requires exactly one expression in ORDER BY partition clause\n");
  3493. res = SqlToYql("SELECT COUNT(*) OVER (ORDER BY key, value RANGE 5 PRECEDING) FROM plato.Input");
  3494. UNIT_ASSERT(!res.Root);
  3495. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:49: Error: RANGE with <offset> PRECEDING/FOLLOWING requires exactly one expression in ORDER BY partition clause\n");
  3496. }
  3497. Y_UNIT_TEST(NoColumnsInFrameBounds) {
  3498. NYql::TAstParseResult res = SqlToYql(
  3499. "SELECT SUM(x) OVER w FROM plato.Input WINDOW w AS (ROWS BETWEEN\n"
  3500. " 1 + key PRECEDING AND 2 + key FOLLOWING);");
  3501. UNIT_ASSERT(!res.Root);
  3502. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:2:6: Error: Column reference \"key\" is not allowed in current scope\n");
  3503. }
  3504. Y_UNIT_TEST(WarnOnEmptyFrameBounds) {
  3505. NYql::TAstParseResult res = SqlToYql(
  3506. "SELECT SUM(x) OVER w FROM plato.Input WINDOW w AS (PARTITION BY key ORDER BY subkey\n"
  3507. "ROWS BETWEEN 10 FOLLOWING AND 5 FOLLOWING)");
  3508. UNIT_ASSERT(res.Root);
  3509. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:2:14: Warning: Used frame specification implies empty window frame, code: 4520\n");
  3510. }
  3511. Y_UNIT_TEST(WarnOnRankWithUnorderedWindow) {
  3512. NYql::TAstParseResult res = SqlToYql("SELECT RANK() OVER w FROM plato.Input WINDOW w AS ()");
  3513. UNIT_ASSERT(res.Root);
  3514. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:8: Warning: Rank() is used with unordered window - all rows will be considered equal to each other, code: 4521\n");
  3515. }
  3516. Y_UNIT_TEST(WarnOnRankExprWithUnorderedWindow) {
  3517. NYql::TAstParseResult res = SqlToYql("SELECT RANK(key) OVER w FROM plato.Input WINDOW w AS ()");
  3518. UNIT_ASSERT(res.Root);
  3519. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:8: Warning: Rank(<expression>) is used with unordered window - the result is likely to be undefined, code: 4521\n");
  3520. }
  3521. Y_UNIT_TEST(AnyAsTableName) {
  3522. NYql::TAstParseResult res = SqlToYql("use plato; select * from any;");
  3523. UNIT_ASSERT(!res.Root);
  3524. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:28: Error: no viable alternative at input 'any;'\n");
  3525. }
  3526. Y_UNIT_TEST(IncorrectOrderOfLambdaOptionalArgs) {
  3527. NYql::TAstParseResult res = SqlToYql("$f = ($x?, $y)->($x + $y); select $f(1);");
  3528. UNIT_ASSERT(!res.Root);
  3529. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:12: Error: Non-optional argument can not follow optional one\n");
  3530. }
  3531. Y_UNIT_TEST(IncorrectOrderOfActionOptionalArgs) {
  3532. NYql::TAstParseResult res = SqlToYql("define action $f($x?, $y) as select $x,$y; end define; do $f(1);");
  3533. UNIT_ASSERT(!res.Root);
  3534. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:23: Error: Non-optional argument can not follow optional one\n");
  3535. }
  3536. Y_UNIT_TEST(NotAllowedQuestionOnNamedNode) {
  3537. NYql::TAstParseResult res = SqlToYql("$f = 1; select $f?;");
  3538. UNIT_ASSERT(!res.Root);
  3539. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:18: Error: Unexpected token '?' at the end of expression\n");
  3540. }
  3541. Y_UNIT_TEST(AnyAndCrossJoin) {
  3542. NYql::TAstParseResult res = SqlToYql("use plato; select * from any Input1 cross join Input2");
  3543. UNIT_ASSERT(!res.Root);
  3544. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:26: Error: ANY should not be used with Cross JOIN\n");
  3545. res = SqlToYql("use plato; select * from Input1 cross join any Input2");
  3546. UNIT_ASSERT(!res.Root);
  3547. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:44: Error: ANY should not be used with Cross JOIN\n");
  3548. }
  3549. Y_UNIT_TEST(AnyWithCartesianProduct) {
  3550. NYql::TAstParseResult res = SqlToYql("pragma AnsiImplicitCrossJoin; use plato; select * from any Input1, Input2");
  3551. UNIT_ASSERT(!res.Root);
  3552. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:56: Error: ANY should not be used with Cross JOIN\n");
  3553. res = SqlToYql("pragma AnsiImplicitCrossJoin; use plato; select * from Input1, any Input2");
  3554. UNIT_ASSERT(!res.Root);
  3555. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:64: Error: ANY should not be used with Cross JOIN\n");
  3556. }
  3557. Y_UNIT_TEST(ErrorPlainEndAsInlineActionTerminator) {
  3558. NYql::TAstParseResult res = SqlToYql(
  3559. "do begin\n"
  3560. " select 1\n"
  3561. "; end\n");
  3562. UNIT_ASSERT(!res.Root);
  3563. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:4:0: Error: missing DO at '<EOF>'\n");
  3564. }
  3565. Y_UNIT_TEST(ErrorMultiWayJoinWithUsing) {
  3566. NYql::TAstParseResult res = SqlToYql(
  3567. "USE plato;\n"
  3568. "PRAGMA DisableSimpleColumns;\n"
  3569. "SELECT *\n"
  3570. "FROM Input1 AS a\n"
  3571. "JOIN Input2 AS b USING(key)\n"
  3572. "JOIN Input3 AS c ON a.key = c.key;\n"
  3573. );
  3574. UNIT_ASSERT(!res.Root);
  3575. UNIT_ASSERT_NO_DIFF(Err2Str(res),
  3576. "<main>:5:24: Error: Multi-way JOINs should be connected with ON clause instead of USING clause\n"
  3577. );
  3578. }
  3579. Y_UNIT_TEST(RequireLabelInFlattenByWithDot) {
  3580. NYql::TAstParseResult res = SqlToYql("select * from plato.Input flatten by x.y");
  3581. UNIT_ASSERT(!res.Root);
  3582. UNIT_ASSERT_NO_DIFF(Err2Str(res),
  3583. "<main>:1:40: Error: Unnamed expression after FLATTEN BY is not allowed\n"
  3584. );
  3585. }
  3586. Y_UNIT_TEST(WarnUnnamedColumns) {
  3587. NYql::TAstParseResult res = SqlToYql(
  3588. "PRAGMA WarnUnnamedColumns;\n"
  3589. "\n"
  3590. "SELECT key, subkey, key || subkey FROM plato.Input ORDER BY subkey;\n");
  3591. UNIT_ASSERT(res.Root);
  3592. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:3:28: Warning: Autogenerated column name column2 will be used for expression, code: 4516\n");
  3593. }
  3594. Y_UNIT_TEST(WarnSourceColumnMismatch) {
  3595. NYql::TAstParseResult res = SqlToYql(
  3596. "insert into plato.Output (key, subkey, new_value, one_more_value) select key as Key, subkey, value, \"x\" from plato.Input;");
  3597. UNIT_ASSERT(res.Root);
  3598. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:51: Warning: Column names in SELECT don't match column specification in parenthesis. \"key\" doesn't match \"Key\". \"new_value\" doesn't match \"value\", code: 4517\n");
  3599. }
  3600. Y_UNIT_TEST(YtCaseInsensitive) {
  3601. NYql::TAstParseResult res = SqlToYql("select * from PlatO.foo;");
  3602. UNIT_ASSERT(res.Root);
  3603. res = SqlToYql("use PlatO; select * from foo;");
  3604. UNIT_ASSERT(res.Root);
  3605. }
  3606. Y_UNIT_TEST(KikimrCaseSensitive) {
  3607. NYql::TAstParseResult res = SqlToYql("select * from PlatO.foo;", 10, "kikimr");
  3608. UNIT_ASSERT(!res.Root);
  3609. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:15: Error: Unknown cluster: PlatO\n");
  3610. res = SqlToYql("use PlatO; select * from foo;", 10, "kikimr");
  3611. UNIT_ASSERT(!res.Root);
  3612. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:5: Error: Unknown cluster: PlatO\n");
  3613. }
  3614. Y_UNIT_TEST(DiscoveryModeForbidden) {
  3615. NYql::TAstParseResult res = SqlToYqlWithMode("insert into plato.Output select * from plato.range(\"\", Input1, Input4)", NSQLTranslation::ESqlMode::DISCOVERY);
  3616. UNIT_ASSERT(!res.Root);
  3617. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:40: Error: range is not allowed in Discovery mode, code: 4600\n");
  3618. res = SqlToYqlWithMode("insert into plato.Output select * from plato.like(\"\", \"Input%\")", NSQLTranslation::ESqlMode::DISCOVERY);
  3619. UNIT_ASSERT(!res.Root);
  3620. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:40: Error: like is not allowed in Discovery mode, code: 4600\n");
  3621. res = SqlToYqlWithMode("insert into plato.Output select * from plato.regexp(\"\", \"Input.\")", NSQLTranslation::ESqlMode::DISCOVERY);
  3622. UNIT_ASSERT(!res.Root);
  3623. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:40: Error: regexp is not allowed in Discovery mode, code: 4600\n");
  3624. res = SqlToYqlWithMode("insert into plato.Output select * from plato.filter(\"\", ($name) -> { return find($name, \"Input\") is not null; })", NSQLTranslation::ESqlMode::DISCOVERY);
  3625. UNIT_ASSERT(!res.Root);
  3626. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:40: Error: filter is not allowed in Discovery mode, code: 4600\n");
  3627. res = SqlToYqlWithMode("select Path from plato.folder(\"\") where Type == \"table\"", NSQLTranslation::ESqlMode::DISCOVERY);
  3628. UNIT_ASSERT(!res.Root);
  3629. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:18: Error: folder is not allowed in Discovery mode, code: 4600\n");
  3630. }
  3631. Y_UNIT_TEST(YsonFuncWithoutArgs) {
  3632. UNIT_ASSERT(SqlToYql("SELECT Yson::SerializeText(Yson::From());").IsOk());
  3633. }
  3634. Y_UNIT_TEST(CanNotUseOrderByInNonLastSelectInUnionAllChain) {
  3635. auto req = "pragma AnsiOrderByLimitInUnionAll;\n"
  3636. "use plato;\n"
  3637. "\n"
  3638. "select * from Input order by key\n"
  3639. "union all\n"
  3640. "select * from Input order by key limit 1;";
  3641. auto res = SqlToYql(req);
  3642. UNIT_ASSERT(!res.Root);
  3643. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:4:21: Error: ORDER BY within UNION ALL is only allowed after last subquery\n");
  3644. }
  3645. Y_UNIT_TEST(CanNotUseLimitInNonLastSelectInUnionAllChain) {
  3646. auto req = "pragma AnsiOrderByLimitInUnionAll;\n"
  3647. "use plato;\n"
  3648. "\n"
  3649. "select * from Input limit 1\n"
  3650. "union all\n"
  3651. "select * from Input order by key limit 1;";
  3652. auto res = SqlToYql(req);
  3653. UNIT_ASSERT(!res.Root);
  3654. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:4:21: Error: LIMIT within UNION ALL is only allowed after last subquery\n");
  3655. }
  3656. Y_UNIT_TEST(CanNotUseDiscardInNonFirstSelectInUnionAllChain) {
  3657. auto req = "pragma AnsiOrderByLimitInUnionAll;\n"
  3658. "use plato;\n"
  3659. "\n"
  3660. "select * from Input\n"
  3661. "union all\n"
  3662. "discard select * from Input;";
  3663. auto res = SqlToYql(req);
  3664. UNIT_ASSERT(!res.Root);
  3665. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:6:1: Error: DISCARD within UNION ALL is only allowed before first subquery\n");
  3666. }
  3667. Y_UNIT_TEST(CanNotUseIntoResultInNonLastSelectInUnionAllChain) {
  3668. auto req = "use plato;\n"
  3669. "pragma AnsiOrderByLimitInUnionAll;\n"
  3670. "\n"
  3671. "select * from Input\n"
  3672. "union all\n"
  3673. "discard select * from Input;";
  3674. auto res = SqlToYql(req);
  3675. UNIT_ASSERT(!res.Root);
  3676. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:6:1: Error: DISCARD within UNION ALL is only allowed before first subquery\n");
  3677. }
  3678. Y_UNIT_TEST(YsonStrictInvalidPragma) {
  3679. auto res = SqlToYql("pragma yson.Strict = \"wrong\";");
  3680. UNIT_ASSERT(!res.Root);
  3681. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:22: Error: Expected 'true', 'false' or no parameter for: Strict\n");
  3682. }
  3683. Y_UNIT_TEST(WarnTableNameInSomeContexts) {
  3684. UNIT_ASSERT(SqlToYql("use plato; select TableName() from Input;").IsOk());
  3685. UNIT_ASSERT(SqlToYql("use plato; select TableName(\"aaaa\");").IsOk());
  3686. UNIT_ASSERT(SqlToYql("select TableName(\"aaaa\", \"yt\");").IsOk());
  3687. auto res = SqlToYql("select TableName() from plato.Input;");
  3688. UNIT_ASSERT(!res.Root);
  3689. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:8: Error: TableName requires either service name as second argument or current cluster name\n");
  3690. res = SqlToYql("use plato;\n"
  3691. "select TableName() from Input1 as a join Input2 as b using(key);");
  3692. UNIT_ASSERT(res.Root);
  3693. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:2:8: Warning: TableName() may produce empty result when used in ambiguous context (with JOIN), code: 4525\n");
  3694. res = SqlToYql("use plato;\n"
  3695. "select SOME(TableName()), key from Input group by key;");
  3696. UNIT_ASSERT(res.Root);
  3697. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:2:13: Warning: TableName() will produce empty result when used with aggregation.\n"
  3698. "Please consult documentation for possible workaround, code: 4525\n");
  3699. }
  3700. Y_UNIT_TEST(WarnOnDistincWithHavingWithoutAggregations) {
  3701. auto res = SqlToYql("select distinct key from plato.Input having key != '0';");
  3702. UNIT_ASSERT(res.Root);
  3703. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:49: Warning: The usage of HAVING without aggregations with SELECT DISTINCT is non-standard and will stop working soon. Please use WHERE instead., code: 4526\n");
  3704. }
  3705. Y_UNIT_TEST(FlattenByExprWithNestedNull) {
  3706. auto res = SqlToYql("USE plato;\n"
  3707. "\n"
  3708. "SELECT * FROM (SELECT 1 AS region_id)\n"
  3709. "FLATTEN BY (\n"
  3710. " CAST($unknown(region_id) AS List<String>) AS region\n"
  3711. ")");
  3712. UNIT_ASSERT(!res.Root);
  3713. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:5:10: Error: Unknown name: $unknown\n");
  3714. }
  3715. Y_UNIT_TEST(EmptySymbolNameIsForbidden) {
  3716. auto req = " $`` = 1; select $``;";
  3717. auto res = SqlToYql(req);
  3718. UNIT_ASSERT(!res.Root);
  3719. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:5: Error: Empty symbol name is not allowed\n");
  3720. }
  3721. Y_UNIT_TEST(WarnOnBinaryOpWithNullArg) {
  3722. auto req = "select * from plato.Input where cast(key as Int32) != NULL";
  3723. auto res = SqlToYql(req);
  3724. UNIT_ASSERT(res.Root);
  3725. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:52: Warning: Binary operation != will return NULL here, code: 4529\n");
  3726. req = "select 1 or null";
  3727. res = SqlToYql(req);
  3728. UNIT_ASSERT(res.Root);
  3729. UNIT_ASSERT_NO_DIFF(Err2Str(res), "");
  3730. }
  3731. Y_UNIT_TEST(ErrorIfTableSampleArgUsesColumns) {
  3732. auto req = "SELECT key FROM plato.Input TABLESAMPLE BERNOULLI(MIN_OF(100.0, CAST(subkey as Int32)));";
  3733. auto res = SqlToYql(req);
  3734. UNIT_ASSERT(!res.Root);
  3735. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:70: Error: Column reference \"subkey\" is not allowed in current scope\n");
  3736. }
  3737. Y_UNIT_TEST(DerivedColumnListForSelectIsNotSupportedYet) {
  3738. auto req = "SELECT a,b,c FROM plato.Input as t(x,y,z);";
  3739. auto res = SqlToYql(req);
  3740. UNIT_ASSERT(!res.Root);
  3741. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:35: Error: Derived column list is only supported for VALUES\n");
  3742. }
  3743. Y_UNIT_TEST(ErrorIfValuesHasDifferentCountOfColumns) {
  3744. auto req = "VALUES (1,2,3), (4,5);";
  3745. auto res = SqlToYql(req);
  3746. UNIT_ASSERT(!res.Root);
  3747. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:17: Error: All VALUES items should have same size: expecting 3, got 2\n");
  3748. }
  3749. Y_UNIT_TEST(ErrorIfDerivedColumnSizeExceedValuesColumnCount) {
  3750. auto req = "SELECT * FROM(VALUES (1,2), (3,4)) as t(x,y,z);";
  3751. auto res = SqlToYql(req);
  3752. UNIT_ASSERT(!res.Root);
  3753. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:40: Error: Derived column list size exceeds column count in VALUES\n");
  3754. }
  3755. Y_UNIT_TEST(WarnoOnAutogeneratedNamesForValues) {
  3756. auto req = "PRAGMA WarnUnnamedColumns;\n"
  3757. "SELECT * FROM (VALUES (1,2,3,4), (5,6,7,8)) as t(x,y);";
  3758. auto res = SqlToYql(req);
  3759. UNIT_ASSERT(res.Root);
  3760. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:2:16: Warning: Autogenerated column names column2...column3 will be used here, code: 4516\n");
  3761. }
  3762. Y_UNIT_TEST(ErrUnionAllWithOrderByWithoutExplicitLegacyMode) {
  3763. auto req = "use plato;\n"
  3764. "\n"
  3765. "select * from Input order by key\n"
  3766. "union all\n"
  3767. "select * from Input order by key;";
  3768. auto res = SqlToYql(req);
  3769. UNIT_ASSERT(!res.Root);
  3770. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:3:21: Error: ORDER BY within UNION ALL is only allowed after last subquery\n");
  3771. }
  3772. Y_UNIT_TEST(ErrUnionAllWithLimitWithoutExplicitLegacyMode) {
  3773. auto req = "use plato;\n"
  3774. "\n"
  3775. "select * from Input limit 10\n"
  3776. "union all\n"
  3777. "select * from Input limit 1;";
  3778. auto res = SqlToYql(req);
  3779. UNIT_ASSERT(!res.Root);
  3780. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:3:21: Error: LIMIT within UNION ALL is only allowed after last subquery\n");
  3781. }
  3782. Y_UNIT_TEST(ErrUnionAllWithIntoResultWithoutExplicitLegacyMode) {
  3783. auto req = "use plato;\n"
  3784. "\n"
  3785. "select * from Input into result aaa\n"
  3786. "union all\n"
  3787. "select * from Input;";
  3788. auto res = SqlToYql(req);
  3789. UNIT_ASSERT(!res.Root);
  3790. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:3:21: Error: INTO RESULT within UNION ALL is only allowed after last subquery\n");
  3791. }
  3792. Y_UNIT_TEST(ErrUnionAllWithDiscardWithoutExplicitLegacyMode) {
  3793. auto req = "use plato;\n"
  3794. "\n"
  3795. "select * from Input\n"
  3796. "union all\n"
  3797. "discard select * from Input;";
  3798. auto res = SqlToYql(req);
  3799. UNIT_ASSERT(!res.Root);
  3800. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:5:1: Error: DISCARD within UNION ALL is only allowed before first subquery\n");
  3801. }
  3802. Y_UNIT_TEST(ErrUnionAllKeepsIgnoredOrderByWarning) {
  3803. auto req = "use plato;\n"
  3804. "\n"
  3805. "SELECT * FROM (\n"
  3806. " SELECT * FROM Input\n"
  3807. " UNION ALL\n"
  3808. " SELECT t.* FROM Input AS t ORDER BY t.key\n"
  3809. ");";
  3810. auto res = SqlToYql(req);
  3811. UNIT_ASSERT(!res.Root);
  3812. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:4:3: Warning: ORDER BY without LIMIT in subquery will be ignored, code: 4504\n"
  3813. "<main>:6:39: Error: Unknown correlation name: t\n");
  3814. }
  3815. Y_UNIT_TEST(ErrOrderByIgnoredButCheckedForMissingColumns) {
  3816. auto req = "$src = SELECT key FROM (SELECT 1 as key, 2 as subkey) ORDER BY x; SELECT * FROM $src;";
  3817. ExpectFailWithError(req, "<main>:1:8: Warning: ORDER BY without LIMIT in subquery will be ignored, code: 4504\n"
  3818. "<main>:1:64: Error: Column x is not in source column set\n");
  3819. req = "$src = SELECT key FROM plato.Input ORDER BY x; SELECT * FROM $src;";
  3820. auto res = SqlToYql(req);
  3821. UNIT_ASSERT(res.Root);
  3822. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:8: Warning: ORDER BY without LIMIT in subquery will be ignored, code: 4504\n");
  3823. }
  3824. Y_UNIT_TEST(InvalidTtlInterval) {
  3825. auto req = R"(
  3826. USE plato;
  3827. CREATE TABLE tableName (Key Uint32, CreatedAt Timestamp, PRIMARY KEY (Key))
  3828. WITH (TTL = 1 On CreatedAt);
  3829. )";
  3830. auto res = SqlToYql(req);
  3831. UNIT_ASSERT(!res.Root);
  3832. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:4:25: Error: Literal of Interval type is expected for TTL\n"
  3833. "<main>:4:25: Error: Invalid TTL settings\n");
  3834. }
  3835. Y_UNIT_TEST(InvalidTtlUnit) {
  3836. auto req = R"(
  3837. USE plato;
  3838. CREATE TABLE tableName (Key Uint32, CreatedAt Uint32, PRIMARY KEY (Key))
  3839. WITH (TTL = Interval("P1D") On CreatedAt AS PICOSECONDS);
  3840. )";
  3841. auto res = SqlToYql(req);
  3842. UNIT_ASSERT(!res.Root);
  3843. UNIT_ASSERT_STRING_CONTAINS(Err2Str(res), "mismatched input 'PICOSECONDS' expecting {MICROSECONDS, MILLISECONDS, NANOSECONDS, SECONDS}");
  3844. }
  3845. Y_UNIT_TEST(InvalidChangefeedSink) {
  3846. auto req = R"(
  3847. USE plato;
  3848. CREATE TABLE tableName (
  3849. Key Uint32, PRIMARY KEY (Key),
  3850. CHANGEFEED feedName WITH (SINK_TYPE = "S3", MODE = "KEYS_ONLY", FORMAT = "json")
  3851. );
  3852. )";
  3853. auto res = SqlToYql(req);
  3854. UNIT_ASSERT(!res.Root);
  3855. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:5:55: Error: Unknown changefeed sink type: S3\n");
  3856. }
  3857. Y_UNIT_TEST(InvalidChangefeedSettings) {
  3858. auto req = R"(
  3859. USE plato;
  3860. CREATE TABLE tableName (
  3861. Key Uint32, PRIMARY KEY (Key),
  3862. CHANGEFEED feedName WITH (SINK_TYPE = "local", FOO = "bar")
  3863. );
  3864. )";
  3865. auto res = SqlToYql(req);
  3866. UNIT_ASSERT(!res.Root);
  3867. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:5:64: Error: Unknown changefeed setting: FOO\n");
  3868. }
  3869. Y_UNIT_TEST(InvalidChangefeedInitialScan) {
  3870. auto req = R"(
  3871. USE plato;
  3872. CREATE TABLE tableName (
  3873. Key Uint32, PRIMARY KEY (Key),
  3874. CHANGEFEED feedName WITH (MODE = "KEYS_ONLY", FORMAT = "json", INITIAL_SCAN = "foo")
  3875. );
  3876. )";
  3877. auto res = SqlToYql(req);
  3878. UNIT_ASSERT(!res.Root);
  3879. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:5:95: Error: Literal of Bool type is expected for INITIAL_SCAN\n");
  3880. }
  3881. Y_UNIT_TEST(InvalidChangefeedVirtualTimestamps) {
  3882. auto req = R"(
  3883. USE plato;
  3884. CREATE TABLE tableName (
  3885. Key Uint32, PRIMARY KEY (Key),
  3886. CHANGEFEED feedName WITH (MODE = "KEYS_ONLY", FORMAT = "json", VIRTUAL_TIMESTAMPS = "foo")
  3887. );
  3888. )";
  3889. auto res = SqlToYql(req);
  3890. UNIT_ASSERT(!res.Root);
  3891. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:5:101: Error: Literal of Bool type is expected for VIRTUAL_TIMESTAMPS\n");
  3892. }
  3893. Y_UNIT_TEST(InvalidChangefeedResolvedTimestamps) {
  3894. auto req = R"(
  3895. USE plato;
  3896. CREATE TABLE tableName (
  3897. Key Uint32, PRIMARY KEY (Key),
  3898. CHANGEFEED feedName WITH (MODE = "KEYS_ONLY", FORMAT = "json", RESOLVED_TIMESTAMPS = "foo")
  3899. );
  3900. )";
  3901. auto res = SqlToYql(req);
  3902. UNIT_ASSERT(!res.Root);
  3903. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:5:102: Error: Literal of Interval type is expected for RESOLVED_TIMESTAMPS\n");
  3904. }
  3905. Y_UNIT_TEST(InvalidChangefeedRetentionPeriod) {
  3906. auto req = R"(
  3907. USE plato;
  3908. CREATE TABLE tableName (
  3909. Key Uint32, PRIMARY KEY (Key),
  3910. CHANGEFEED feedName WITH (MODE = "KEYS_ONLY", FORMAT = "json", RETENTION_PERIOD = "foo")
  3911. );
  3912. )";
  3913. auto res = SqlToYql(req);
  3914. UNIT_ASSERT(!res.Root);
  3915. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:5:99: Error: Literal of Interval type is expected for RETENTION_PERIOD\n");
  3916. }
  3917. Y_UNIT_TEST(InvalidChangefeedTopicPartitions) {
  3918. auto req = R"(
  3919. USE plato;
  3920. CREATE TABLE tableName (
  3921. Key Uint32, PRIMARY KEY (Key),
  3922. CHANGEFEED feedName WITH (MODE = "KEYS_ONLY", FORMAT = "json", TOPIC_MIN_ACTIVE_PARTITIONS = "foo")
  3923. );
  3924. )";
  3925. auto res = SqlToYql(req);
  3926. UNIT_ASSERT(!res.Root);
  3927. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:5:110: Error: Literal of integer type is expected for TOPIC_MIN_ACTIVE_PARTITIONS\n");
  3928. }
  3929. Y_UNIT_TEST(InvalidChangefeedAwsRegion) {
  3930. auto req = R"(
  3931. USE plato;
  3932. CREATE TABLE tableName (
  3933. Key Uint32, PRIMARY KEY (Key),
  3934. CHANGEFEED feedName WITH (MODE = "KEYS_ONLY", FORMAT = "json", AWS_REGION = true)
  3935. );
  3936. )";
  3937. auto res = SqlToYql(req);
  3938. UNIT_ASSERT(!res.Root);
  3939. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:5:93: Error: Literal of String type is expected for AWS_REGION\n");
  3940. }
  3941. Y_UNIT_TEST(ErrJoinWithGroupingSetsWithoutCorrelationName) {
  3942. auto req = "USE plato;\n"
  3943. "\n"
  3944. "SELECT k1, k2, subkey\n"
  3945. "FROM T1 AS a JOIN T2 AS b USING (key)\n"
  3946. "GROUP BY GROUPING SETS(\n"
  3947. " (a.key as k1, b.subkey as k2),\n"
  3948. " (k1),\n"
  3949. " (subkey)\n"
  3950. ");";
  3951. auto res = SqlToYql(req);
  3952. UNIT_ASSERT(!res.Root);
  3953. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:8:4: Error: Columns in grouping sets should have correlation name, error in key: subkey\n");
  3954. }
  3955. Y_UNIT_TEST(ErrJoinWithGroupByWithoutCorrelationName) {
  3956. auto req = "USE plato;\n"
  3957. "\n"
  3958. "SELECT k1, k2,\n"
  3959. " value\n"
  3960. "FROM T1 AS a JOIN T2 AS b USING (key)\n"
  3961. "GROUP BY a.key as k1, b.subkey as k2,\n"
  3962. " value;";
  3963. ExpectFailWithError(req,
  3964. "<main>:7:5: Error: Columns in GROUP BY should have correlation name, error in key: value\n");
  3965. }
  3966. Y_UNIT_TEST(ErrWithMissingFrom) {
  3967. auto req = "select 1 as key where 1 > 1;";
  3968. auto res = SqlToYql(req);
  3969. UNIT_ASSERT(!res.Root);
  3970. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:25: Error: Filtering is not allowed without FROM\n");
  3971. req = "select 1 + count(*);";
  3972. res = SqlToYql(req);
  3973. UNIT_ASSERT(!res.Root);
  3974. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:12: Error: Aggregation is not allowed without FROM\n");
  3975. req = "select 1 as key, subkey + value;";
  3976. res = SqlToYql(req);
  3977. UNIT_ASSERT(!res.Root);
  3978. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:1: Error: Column references are not allowed without FROM\n"
  3979. "<main>:1:18: Error: Column reference 'subkey'\n"
  3980. "<main>:1:1: Error: Column references are not allowed without FROM\n"
  3981. "<main>:1:27: Error: Column reference 'value'\n");
  3982. req = "select count(1) group by key;";
  3983. res = SqlToYql(req);
  3984. UNIT_ASSERT(!res.Root);
  3985. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:1: Error: Column references are not allowed without FROM\n"
  3986. "<main>:1:26: Error: Column reference 'key'\n");
  3987. }
  3988. Y_UNIT_TEST(ErrWithMissingFromForWindow) {
  3989. auto req = "$c = () -> (1 + count(1) over w);\n"
  3990. "select $c();";
  3991. ExpectFailWithError(req,
  3992. "<main>:1:9: Error: Window and aggregation functions are not allowed in this context\n"
  3993. "<main>:1:17: Error: Failed to use aggregation function Count without window specification or in wrong place\n");
  3994. req = "$c = () -> (1 + lead(1) over w);\n"
  3995. "select $c();";
  3996. ExpectFailWithError(req,
  3997. "<main>:1:17: Error: Window functions are not allowed in this context\n"
  3998. "<main>:1:17: Error: Failed to use window function Lead without window specification or in wrong place\n");
  3999. req = "select 1 + count(1) over w window w as ();";
  4000. ExpectFailWithError(req,
  4001. "<main>:1:1: Error: Window and aggregation functions are not allowed without FROM\n"
  4002. "<main>:1:12: Error: Failed to use aggregation function Count without window specification or in wrong place\n");
  4003. req = "select 1 + lead(1) over w window w as ();";
  4004. ExpectFailWithError(req,
  4005. "<main>:1:12: Error: Window functions are not allowed without FROM\n"
  4006. "<main>:1:12: Error: Failed to use window function Lead without window specification or in wrong place\n");
  4007. }
  4008. Y_UNIT_TEST(ErrWithMissingFromForInplaceWindow) {
  4009. auto req = "$c = () -> (1 + count(1) over ());\n"
  4010. "select $c();";
  4011. ExpectFailWithError(req,
  4012. "<main>:1:26: Error: Window and aggregation functions are not allowed in this context\n");
  4013. req = "$c = () -> (1 + lead(1) over (rows between unbounded preceding and current row));\n"
  4014. "select $c();";
  4015. ExpectFailWithError(req,
  4016. "<main>:1:25: Error: Window and aggregation functions are not allowed in this context\n");
  4017. req = "select 1 + count(1) over ();";
  4018. ExpectFailWithError(req,
  4019. "<main>:1:1: Error: Window and aggregation functions are not allowed without FROM\n"
  4020. "<main>:1:12: Error: Failed to use aggregation function Count without window specification or in wrong place\n");
  4021. req = "select 1 + lead(1) over (rows between current row and unbounded following);";
  4022. ExpectFailWithError(req,
  4023. "<main>:1:12: Error: Window functions are not allowed without FROM\n"
  4024. "<main>:1:12: Error: Failed to use window function Lead without window specification or in wrong place\n");
  4025. }
  4026. Y_UNIT_TEST(ErrDistinctInWrongPlace) {
  4027. auto req = "select Some::Udf(distinct key) from plato.Input;";
  4028. ExpectFailWithError(req,
  4029. "<main>:1:18: Error: DISTINCT can only be used in aggregation functions\n");
  4030. req = "select sum(key)(distinct foo) from plato.Input;";
  4031. ExpectFailWithError(req,
  4032. "<main>:1:17: Error: DISTINCT can only be used in aggregation functions\n");
  4033. req = "select len(distinct foo) from plato.Input;";
  4034. ExpectFailWithError(req,
  4035. "<main>:1:8: Error: DISTINCT can only be used in aggregation functions\n");
  4036. req = "$foo = ($x) -> ($x); select $foo(distinct key) from plato.Input;";
  4037. ExpectFailWithError(req,
  4038. "<main>:1:34: Error: DISTINCT can only be used in aggregation functions\n");
  4039. }
  4040. Y_UNIT_TEST(ErrForNotSingleChildInInlineAST) {
  4041. ExpectFailWithError("select YQL::\"\"",
  4042. "<main>:1:8: Error: Failed to parse YQL: expecting AST root node with single child, but got 0\n");
  4043. ExpectFailWithError("select YQL::@@ \t@@",
  4044. "<main>:1:8: Error: Failed to parse YQL: expecting AST root node with single child, but got 0\n");
  4045. auto req = "$lambda = YQL::@@(lambda '(x)(+ x x)) (lambda '(y)(+ y y))@@;\n"
  4046. "select ListMap([1, 2, 3], $lambda);";
  4047. ExpectFailWithError(req,
  4048. "<main>:1:11: Error: Failed to parse YQL: expecting AST root node with single child, but got 2\n");
  4049. }
  4050. Y_UNIT_TEST(ErrEmptyColumnName) {
  4051. ExpectFailWithError("select * without \"\" from plato.Input",
  4052. "<main>:1:18: Error: String literal can not be used here\n");
  4053. ExpectFailWithError("select * without `` from plato.Input;",
  4054. "<main>:1:18: Error: Empty column name is not allowed\n");
  4055. ExpectFailWithErrorForAnsiLexer("select * without \"\" from plato.Input",
  4056. "<main>:1:18: Error: Empty column name is not allowed\n");
  4057. ExpectFailWithErrorForAnsiLexer("select * without `` from plato.Input;",
  4058. "<main>:1:18: Error: Empty column name is not allowed\n");
  4059. }
  4060. Y_UNIT_TEST(ErrOnNonZeroArgumentsForTableRows) {
  4061. ExpectFailWithError("$udf=\"\";process plato.Input using $udf(TableRows(k))",
  4062. "<main>:1:40: Error: TableRows requires exactly 0 arguments\n");
  4063. }
  4064. Y_UNIT_TEST(ErrGroupByWithAggregationFunctionAndDistinctExpr) {
  4065. ExpectFailWithError("select * from plato.Input group by count(distinct key|key)",
  4066. "<main>:1:36: Error: Unable to GROUP BY aggregated values\n");
  4067. }
  4068. // FIXME: check if we can get old behaviour
  4069. #if 0
  4070. Y_UNIT_TEST(ErrWithSchemaWithColumnsWithoutType) {
  4071. ExpectFailWithError("select * from plato.Input with COLUMNs",
  4072. "<main>:1:32: Error: Expected type after COLUMNS\n"
  4073. "<main>:1:32: Error: Failed to parse table hints\n");
  4074. ExpectFailWithError("select * from plato.Input with scheMa",
  4075. "<main>:1:32: Error: Expected type after SCHEMA\n"
  4076. "<main>:1:32: Error: Failed to parse table hints\n");
  4077. }
  4078. #endif
  4079. Y_UNIT_TEST(ErrCollectPreaggregatedInListLiteralWithoutFrom) {
  4080. ExpectFailWithError("SELECT([VARIANCE(DISTINCT[])])",
  4081. "<main>:1:1: Error: Column references are not allowed without FROM\n"
  4082. "<main>:1:9: Error: Column reference '_yql_preagg_Variance0'\n");
  4083. }
  4084. Y_UNIT_TEST(ErrGroupBySmartParenAsTuple) {
  4085. ExpectFailWithError("SELECT * FROM plato.Input GROUP BY (k, v,)",
  4086. "<main>:1:41: Error: Unexpected trailing comma in grouping elements list\n");
  4087. }
  4088. Y_UNIT_TEST(HandleNestedSmartParensInGroupBy) {
  4089. ExpectFailWithError("SELECT * FROM plato.Input GROUP BY (+() as k)",
  4090. "<main>:1:37: Error: Unable to GROUP BY constant expression\n");
  4091. }
  4092. Y_UNIT_TEST(ErrRenameWithAddColumn) {
  4093. ExpectFailWithError("USE plato; ALTER TABLE table RENAME TO moved, ADD COLUMN addc uint64",
  4094. "<main>:1:40: Error: RENAME TO can not be used together with another table action\n");
  4095. }
  4096. Y_UNIT_TEST(ErrAddColumnAndRename) {
  4097. // FIXME: fix positions in ALTER TABLE
  4098. ExpectFailWithError("USE plato; ALTER TABLE table ADD COLUMN addc uint64, RENAME TO moved",
  4099. "<main>:1:46: Error: RENAME TO can not be used together with another table action\n");
  4100. }
  4101. Y_UNIT_TEST(InvalidUuidValue) {
  4102. ExpectFailWithError("SELECT Uuid('123e4567ae89ba12d3aa456a426614174ab0')",
  4103. "<main>:1:8: Error: Invalid value \"123e4567ae89ba12d3aa456a426614174ab0\" for type Uuid\n");
  4104. ExpectFailWithError("SELECT Uuid('123e4567ae89b-12d3-a456-426614174000')",
  4105. "<main>:1:8: Error: Invalid value \"123e4567ae89b-12d3-a456-426614174000\" for type Uuid\n");
  4106. }
  4107. Y_UNIT_TEST(WindowFunctionWithoutOver) {
  4108. ExpectFailWithError("SELECT LAST_VALUE(foo) FROM plato.Input",
  4109. "<main>:1:8: Error: Can't use window function LastValue without window specification (OVER keyword is missing)\n");
  4110. ExpectFailWithError("SELECT LAST_VALUE(foo) FROM plato.Input GROUP BY key",
  4111. "<main>:1:8: Error: Can't use window function LastValue without window specification (OVER keyword is missing)\n");
  4112. }
  4113. Y_UNIT_TEST(CreateAlterUserWithoutCluster) {
  4114. ExpectFailWithError("\n CREATE USER user ENCRYPTED PASSWORD 'foobar';", "<main>:2:2: Error: USE statement is missing - no default cluster is selected\n");
  4115. ExpectFailWithError("ALTER USER CURRENT_USER RENAME TO $foo;", "<main>:1:1: Error: USE statement is missing - no default cluster is selected\n");
  4116. }
  4117. Y_UNIT_TEST(ModifyPermissionsWithoutCluster) {
  4118. ExpectFailWithError("\n GRANT CONNECT ON `/Root` TO user;", "<main>:2:2: Error: USE statement is missing - no default cluster is selected\n");
  4119. ExpectFailWithError("\n REVOKE MANAGE ON `/Root` FROM user;", "<main>:2:2: Error: USE statement is missing - no default cluster is selected\n");
  4120. }
  4121. Y_UNIT_TEST(ReservedRoleNames) {
  4122. ExpectFailWithError("USE plato; CREATE USER current_User;", "<main>:1:24: Error: System role CURRENT_USER can not be used here\n");
  4123. ExpectFailWithError("USE plato; ALTER USER current_User RENAME TO Current_role", "<main>:1:46: Error: System role CURRENT_ROLE can not be used here\n");
  4124. UNIT_ASSERT(SqlToYql("USE plato; DROP GROUP IF EXISTS a, b, c, current_User;").IsOk());
  4125. }
  4126. Y_UNIT_TEST(DisableClassicDivisionWithError) {
  4127. ExpectFailWithError("pragma ClassicDivision = 'false'; select $foo / 30;", "<main>:1:42: Error: Unknown name: $foo\n");
  4128. }
  4129. Y_UNIT_TEST(AggregationOfAgrregatedDistinctExpr) {
  4130. ExpectFailWithError("select sum(sum(distinct x + 1)) from plato.Input", "<main>:1:12: Error: Aggregation of aggregated values is forbidden\n");
  4131. }
  4132. Y_UNIT_TEST(WarnForUnusedSqlHint) {
  4133. NYql::TAstParseResult res = SqlToYql("select * from plato.Input1 as a join /*+ merge() */ plato.Input2 as b using(key);\n"
  4134. "select --+ foo(bar)\n"
  4135. " 1;");
  4136. UNIT_ASSERT(res.Root);
  4137. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:2:23: Warning: Hint foo will not be used, code: 4534\n");
  4138. }
  4139. Y_UNIT_TEST(WarnForDeprecatedSchema) {
  4140. NSQLTranslation::TTranslationSettings settings;
  4141. settings.ClusterMapping["s3bucket"] = NYql::S3ProviderName;
  4142. NYql::TAstParseResult res = SqlToYql("select * from s3bucket.`foo` with schema (col1 Int32, String as col2, Int64 as col3);", settings);
  4143. UNIT_ASSERT(res.Root);
  4144. UNIT_ASSERT_STRING_CONTAINS(res.Issues.ToString(), "Warning: Deprecated syntax for positional schema: please use 'column type' instead of 'type AS column', code: 4535\n");
  4145. }
  4146. Y_UNIT_TEST(ErrorOnColumnNameInMaxByLimit) {
  4147. ExpectFailWithError(
  4148. "SELECT AGGREGATE_BY(AsTuple(value, key), AggregationFactory(\"MAX_BY\", subkey)) FROM plato.Input;",
  4149. "<main>:1:42: Error: Source does not allow column references\n"
  4150. "<main>:1:71: Error: Column reference 'subkey'\n");
  4151. }
  4152. Y_UNIT_TEST(ErrorInLibraryWithTopLevelNamedSubquery) {
  4153. TString withUnusedSubq = "$unused = select max(key) from plato.Input;\n"
  4154. "\n"
  4155. "define subquery $foo() as\n"
  4156. " $count = select count(*) from plato.Input;\n"
  4157. " select * from plato.Input limit $count / 2;\n"
  4158. "end define;\n"
  4159. "export $foo;\n";
  4160. UNIT_ASSERT(SqlToYqlWithMode(withUnusedSubq, NSQLTranslation::ESqlMode::LIBRARY).IsOk());
  4161. TString withTopLevelSubq = "$count = select count(*) from plato.Input;\n"
  4162. "\n"
  4163. "define subquery $foo() as\n"
  4164. " select * from plato.Input limit $count / 2;\n"
  4165. "end define;\n"
  4166. "export $foo;\n";
  4167. auto res = SqlToYqlWithMode(withTopLevelSubq, NSQLTranslation::ESqlMode::LIBRARY);
  4168. UNIT_ASSERT(!res.Root);
  4169. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:17: Error: Named subquery can not be used as a top level statement in libraries\n");
  4170. }
  4171. Y_UNIT_TEST(SessionStartAndSessionStateShouldSurviveSessionWindowArgsError){
  4172. TString query = R"(
  4173. $init = ($_row) -> (min(1, 2)); -- error: aggregation func min() can not be used here
  4174. $calculate = ($_row, $_state) -> (1);
  4175. $update = ($_row, $_state) -> (2);
  4176. SELECT
  4177. SessionStart() over w as session_start,
  4178. SessionState() over w as session_state,
  4179. FROM plato.Input as t
  4180. WINDOW w AS (
  4181. PARTITION BY user, SessionWindow(ts + 1, $init, $update, $calculate)
  4182. )
  4183. )";
  4184. ExpectFailWithError(query, "<main>:2:33: Error: Aggregation function Min requires exactly 1 argument(s), given: 2\n");
  4185. }
  4186. }
  4187. void CheckUnused(const TString& req, const TString& symbol, unsigned row, unsigned col) {
  4188. auto res = SqlToYql(req);
  4189. UNIT_ASSERT(res.Root);
  4190. UNIT_ASSERT_NO_DIFF(Err2Str(res), TStringBuilder() << "<main>:" << row << ":" << col << ": Warning: Symbol " << symbol << " is not used, code: 4527\n");
  4191. }
  4192. Y_UNIT_TEST_SUITE(WarnUnused) {
  4193. Y_UNIT_TEST(ActionOrSubquery) {
  4194. TString req = " $a()\n"
  4195. "as select 1;\n"
  4196. "end define;\n"
  4197. "\n"
  4198. "select 1;";
  4199. CheckUnused("define action\n" + req, "$a", 2, 3);
  4200. CheckUnused("define subquery\n" + req, "$a", 2, 3);
  4201. }
  4202. Y_UNIT_TEST(Import) {
  4203. TString req = "import lib1 symbols\n"
  4204. " $sqr;\n"
  4205. "select 1;";
  4206. CheckUnused(req, "$sqr", 2, 3);
  4207. req = "import lib1 symbols\n"
  4208. " $sqr as\n"
  4209. " $sq;\n"
  4210. "select 1;";
  4211. CheckUnused(req, "$sq", 3, 5);
  4212. }
  4213. Y_UNIT_TEST(NamedNodeStatement) {
  4214. TString req = " $a, $a = AsTuple(1, 2);\n"
  4215. "select $a;";
  4216. CheckUnused(req, "$a", 1, 2);
  4217. req = "$a, $b = AsTuple(1, 2);\n"
  4218. "select $a;";
  4219. CheckUnused(req, "$b", 1, 6);
  4220. CheckUnused(" $a = 1; $a = 2; select $a;", "$a", 1, 2);
  4221. }
  4222. Y_UNIT_TEST(Declare) {
  4223. CheckUnused("declare $a as String;select 1;", "$a", 1, 9);
  4224. }
  4225. Y_UNIT_TEST(ActionParams) {
  4226. TString req = "define action $a($x, $y) as\n"
  4227. " select $x;\n"
  4228. "end define;\n"
  4229. "\n"
  4230. "do $a(1,2);";
  4231. CheckUnused(req, "$y", 1, 22);
  4232. }
  4233. Y_UNIT_TEST(SubqueryParams) {
  4234. TString req = "use plato;\n"
  4235. "define subquery $q($name, $x) as\n"
  4236. " select * from $name;\n"
  4237. "end define;\n"
  4238. "\n"
  4239. "select * from $q(\"Input\", 1);";
  4240. CheckUnused(req, "$x", 2, 27);
  4241. }
  4242. Y_UNIT_TEST(For) {
  4243. TString req = "define action $a() as\n"
  4244. " select 1;\n"
  4245. "end define;\n"
  4246. "\n"
  4247. "for $i in ListFromRange(1, 10)\n"
  4248. "do $a();";
  4249. CheckUnused(req, "$i", 5, 5);
  4250. }
  4251. Y_UNIT_TEST(LambdaParams) {
  4252. TString req = "$lambda = ($x, $y) -> ($x);\n"
  4253. "select $lambda(1, 2);";
  4254. CheckUnused(req, "$y", 1, 16);
  4255. }
  4256. Y_UNIT_TEST(InsideLambdaBody) {
  4257. TString req = "$lambda = () -> {\n"
  4258. " $x = 1; return 1;\n"
  4259. "};\n"
  4260. "select $lambda();";
  4261. CheckUnused(req, "$x", 2, 3);
  4262. req = "$lambda = () -> {\n"
  4263. " $x = 1; $x = 2; return $x;\n"
  4264. "};\n"
  4265. "select $lambda();";
  4266. CheckUnused(req, "$x", 2, 3);
  4267. }
  4268. Y_UNIT_TEST(InsideAction) {
  4269. TString req = "define action $a() as\n"
  4270. " $x = 1; select 1;\n"
  4271. "end define;\n"
  4272. "\n"
  4273. "do $a();";
  4274. CheckUnused(req, "$x", 2, 3);
  4275. req = "define action $a() as\n"
  4276. " $x = 1; $x = 2; select $x;\n"
  4277. "end define;\n"
  4278. "\n"
  4279. "do $a();";
  4280. CheckUnused(req, "$x", 2, 3);
  4281. }
  4282. Y_UNIT_TEST(NoWarnOnNestedActions) {
  4283. auto req = "pragma warning(\"error\", \"4527\");\n"
  4284. "define action $action($b) as\n"
  4285. " define action $aaa() as\n"
  4286. " select $b;\n"
  4287. " end define;\n"
  4288. " do $aaa();\n"
  4289. "end define;\n"
  4290. "\n"
  4291. "do $action(1);";
  4292. UNIT_ASSERT(SqlToYql(req).IsOk());
  4293. }
  4294. Y_UNIT_TEST(NoWarnForUsageAfterSubquery) {
  4295. auto req = "use plato;\n"
  4296. "pragma warning(\"error\", \"4527\");\n"
  4297. "\n"
  4298. "$a = 1;\n"
  4299. "\n"
  4300. "define subquery $q($table) as\n"
  4301. " select * from $table;\n"
  4302. "end define;\n"
  4303. "\n"
  4304. "select * from $q(\"Input\");\n"
  4305. "select $a;";
  4306. UNIT_ASSERT(SqlToYql(req).IsOk());
  4307. }
  4308. }
  4309. Y_UNIT_TEST_SUITE(AnonymousNames) {
  4310. Y_UNIT_TEST(ReferenceAnonymousVariableIsForbidden) {
  4311. auto req = "$_ = 1; select $_;";
  4312. auto res = SqlToYql(req);
  4313. UNIT_ASSERT(!res.Root);
  4314. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:16: Error: Unable to reference anonymous name $_\n");
  4315. req = "$`_` = 1; select $`_`;";
  4316. res = SqlToYql(req);
  4317. UNIT_ASSERT(!res.Root);
  4318. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:18: Error: Unable to reference anonymous name $_\n");
  4319. }
  4320. Y_UNIT_TEST(Declare) {
  4321. auto req = "declare $_ as String;";
  4322. auto res = SqlToYql(req);
  4323. UNIT_ASSERT(!res.Root);
  4324. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:9: Error: Can not use anonymous name '$_' in DECLARE statement\n");
  4325. }
  4326. Y_UNIT_TEST(ActionSubquery) {
  4327. auto req = "define action $_() as select 1; end define;";
  4328. auto res = SqlToYql(req);
  4329. UNIT_ASSERT(!res.Root);
  4330. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:15: Error: Can not use anonymous name '$_' as ACTION name\n");
  4331. req = "define subquery $_() as select 1; end define;";
  4332. res = SqlToYql(req);
  4333. UNIT_ASSERT(!res.Root);
  4334. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:17: Error: Can not use anonymous name '$_' as SUBQUERY name\n");
  4335. }
  4336. Y_UNIT_TEST(Import) {
  4337. auto req = "import lib symbols $sqr as $_;";
  4338. auto res = SqlToYql(req);
  4339. UNIT_ASSERT(!res.Root);
  4340. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:28: Error: Can not import anonymous name $_\n");
  4341. }
  4342. Y_UNIT_TEST(Export) {
  4343. auto req = "export $_;";
  4344. auto res = SqlToYqlWithMode(req, NSQLTranslation::ESqlMode::LIBRARY);
  4345. UNIT_ASSERT(!res.Root);
  4346. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:8: Error: Can not export anonymous name $_\n");
  4347. }
  4348. Y_UNIT_TEST(AnonymousInActionArgs) {
  4349. auto req = "pragma warning(\"error\", \"4527\");\n"
  4350. "define action $a($_, $y, $_) as\n"
  4351. " select $y;\n"
  4352. "end define;\n"
  4353. "\n"
  4354. "do $a(1,2,3);";
  4355. UNIT_ASSERT(SqlToYql(req).IsOk());
  4356. }
  4357. Y_UNIT_TEST(AnonymousInSubqueryArgs) {
  4358. auto req = "use plato;\n"
  4359. "pragma warning(\"error\", \"4527\");\n"
  4360. "define subquery $q($_, $y, $_) as\n"
  4361. " select * from $y;\n"
  4362. "end define;\n"
  4363. "\n"
  4364. "select * from $q(1,\"Input\",3);";
  4365. UNIT_ASSERT(SqlToYql(req).IsOk());
  4366. }
  4367. Y_UNIT_TEST(AnonymousInLambdaArgs) {
  4368. auto req = "pragma warning(\"error\", \"4527\");\n"
  4369. "$lambda = ($_, $x, $_) -> ($x);\n"
  4370. "select $lambda(1,2,3);";
  4371. UNIT_ASSERT(SqlToYql(req).IsOk());
  4372. }
  4373. Y_UNIT_TEST(AnonymousInFor) {
  4374. auto req = "pragma warning(\"error\", \"4527\");\n"
  4375. "evaluate for $_ in ListFromRange(1, 10) do begin select 1; end do;";
  4376. UNIT_ASSERT(SqlToYql(req).IsOk());
  4377. }
  4378. Y_UNIT_TEST(Assignment) {
  4379. auto req = "pragma warning(\"error\", \"4527\");\n"
  4380. "$_ = 1;\n"
  4381. "$_, $x, $_ = AsTuple(1,2,3);\n"
  4382. "select $x;";
  4383. UNIT_ASSERT(SqlToYql(req).IsOk());
  4384. }
  4385. }
  4386. Y_UNIT_TEST_SUITE(JsonValue) {
  4387. Y_UNIT_TEST(JsonValueArgumentCount) {
  4388. NYql::TAstParseResult res = SqlToYql("select JSON_VALUE(CAST(@@{\"key\": 1238}@@ as Json));");
  4389. UNIT_ASSERT(!res.Root);
  4390. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:49: Error: mismatched input ')' expecting ','\n");
  4391. }
  4392. Y_UNIT_TEST(JsonValueJsonPathMustBeLiteralString) {
  4393. NYql::TAstParseResult res = SqlToYql("$jsonPath = \"strict $.key\"; select JSON_VALUE(CAST(@@{\"key\": 1238}@@ as Json), $jsonPath);");
  4394. UNIT_ASSERT(!res.Root);
  4395. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:79: Error: mismatched input '$' expecting STRING_VALUE\n");
  4396. }
  4397. Y_UNIT_TEST(JsonValueTranslation) {
  4398. NYql::TAstParseResult res = SqlToYql("select JSON_VALUE(CAST(@@{\"key\": 1238}@@ as Json), \"strict $.key\");");
  4399. UNIT_ASSERT(res.Root);
  4400. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  4401. Y_UNUSED(word);
  4402. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("'\"strict $.key\""));
  4403. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("SafeCast"));
  4404. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("DataType 'Json"));
  4405. };
  4406. TWordCountHive elementStat({"JsonValue"});
  4407. VerifyProgram(res, elementStat, verifyLine);
  4408. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["JsonValue"]);
  4409. }
  4410. Y_UNIT_TEST(JsonValueReturningSection) {
  4411. for (const auto& typeName : {"Bool", "Int64", "Double", "String"}) {
  4412. NYql::TAstParseResult res = SqlToYql(
  4413. TStringBuilder() << "select JSON_VALUE(CAST(@@{\"key\": 1238}@@ as Json), \"strict $.key\" RETURNING " << typeName << ");"
  4414. );
  4415. UNIT_ASSERT(res.Root);
  4416. TVerifyLineFunc verifyLine = [&](const TString& word, const TString& line) {
  4417. Y_UNUSED(word);
  4418. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("'\"strict $.key\""));
  4419. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("SafeCast"));
  4420. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("DataType 'Json"));
  4421. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(TStringBuilder() << "DataType '" << typeName));
  4422. };
  4423. TWordCountHive elementStat({typeName});
  4424. VerifyProgram(res, elementStat, verifyLine);
  4425. UNIT_ASSERT(elementStat[typeName] > 0);
  4426. }
  4427. }
  4428. Y_UNIT_TEST(JsonValueInvalidReturningType) {
  4429. NYql::TAstParseResult res = SqlToYql("select JSON_VALUE(CAST(@@{'key': 1238}@@ as Json), 'strict $.key' RETURNING invalid);");
  4430. UNIT_ASSERT(!res.Root);
  4431. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:77: Error: Unknown simple type 'invalid'\n");
  4432. }
  4433. Y_UNIT_TEST(JsonValueAndReturningInExpressions) {
  4434. NYql::TAstParseResult res = SqlToYql(
  4435. "USE plato\n;"
  4436. "$json_value = \"some string\";\n"
  4437. "SELECT $json_value;\n"
  4438. "SELECT 1 as json_value;\n"
  4439. "SELECT $json_value as json_value;\n"
  4440. "$returning = \"another string\";\n"
  4441. "SELECT $returning;\n"
  4442. "SELECT 1 as returning;\n"
  4443. "SELECT $returning as returning;\n"
  4444. );
  4445. UNIT_ASSERT(res.Root);
  4446. }
  4447. Y_UNIT_TEST(JsonValueValidCaseHandlers) {
  4448. const TVector<std::pair<TString, TString>> testCases = {
  4449. {"", "'DefaultValue (Null)"},
  4450. {"NULL", "'DefaultValue (Null)"},
  4451. {"ERROR", "'Error (Null)"},
  4452. {"DEFAULT 123", "'DefaultValue (Int32 '\"123\")"},
  4453. };
  4454. for (const auto& onEmpty : testCases) {
  4455. for (const auto& onError : testCases) {
  4456. TStringBuilder query;
  4457. query << "$json = CAST(@@{\"key\": 1238}@@ as Json);\n"
  4458. << "SELECT JSON_VALUE($json, \"strict $.key\"";
  4459. if (!onEmpty.first.empty()) {
  4460. query << " " << onEmpty.first << " ON EMPTY";
  4461. }
  4462. if (!onError.first.empty()) {
  4463. query << " " << onError.first << " ON ERROR";
  4464. }
  4465. query << ");\n";
  4466. NYql::TAstParseResult res = SqlToYql(query);
  4467. UNIT_ASSERT(res.Root);
  4468. TVerifyLineFunc verifyLine = [&](const TString& word, const TString& line) {
  4469. Y_UNUSED(word);
  4470. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(onEmpty.second + " " + onError.second));
  4471. };
  4472. TWordCountHive elementStat({"JsonValue"});
  4473. VerifyProgram(res, elementStat, verifyLine);
  4474. UNIT_ASSERT(elementStat["JsonValue"] > 0);
  4475. }
  4476. }
  4477. }
  4478. Y_UNIT_TEST(JsonValueTooManyCaseHandlers) {
  4479. NYql::TAstParseResult res = SqlToYql(
  4480. "select JSON_VALUE(CAST(@@{\"key\": 1238}@@ as Json), \"strict $.key\" NULL ON EMPTY NULL ON ERROR NULL ON EMPTY);\n"
  4481. );
  4482. UNIT_ASSERT(!res.Root);
  4483. UNIT_ASSERT_NO_DIFF(
  4484. Err2Str(res),
  4485. "<main>:1:52: Error: Only 1 ON EMPTY and/or 1 ON ERROR clause is expected\n"
  4486. );
  4487. }
  4488. Y_UNIT_TEST(JsonValueTooManyOnEmpty) {
  4489. NYql::TAstParseResult res = SqlToYql(
  4490. "select JSON_VALUE(CAST(@@{\"key\": 1238}@@ as Json), \"strict $.key\" NULL ON EMPTY NULL ON EMPTY);\n"
  4491. );
  4492. UNIT_ASSERT(!res.Root);
  4493. UNIT_ASSERT_NO_DIFF(
  4494. Err2Str(res),
  4495. "<main>:1:52: Error: Only 1 ON EMPTY clause is expected\n"
  4496. );
  4497. }
  4498. Y_UNIT_TEST(JsonValueTooManyOnError) {
  4499. NYql::TAstParseResult res = SqlToYql(
  4500. "select JSON_VALUE(CAST(@@{\"key\": 1238}@@ as Json), \"strict $.key\" NULL ON ERROR NULL ON ERROR);\n"
  4501. );
  4502. UNIT_ASSERT(!res.Root);
  4503. UNIT_ASSERT_NO_DIFF(
  4504. Err2Str(res),
  4505. "<main>:1:52: Error: Only 1 ON ERROR clause is expected\n"
  4506. );
  4507. }
  4508. Y_UNIT_TEST(JsonValueOnEmptyAfterOnError) {
  4509. NYql::TAstParseResult res = SqlToYql(
  4510. "select JSON_VALUE(CAST(@@{\"key\": 1238}@@ as Json), \"strict $.key\" NULL ON ERROR NULL ON EMPTY);\n"
  4511. );
  4512. UNIT_ASSERT(!res.Root);
  4513. UNIT_ASSERT_NO_DIFF(
  4514. Err2Str(res),
  4515. "<main>:1:52: Error: ON EMPTY clause must be before ON ERROR clause\n"
  4516. );
  4517. }
  4518. Y_UNIT_TEST(JsonValueNullInput) {
  4519. NYql::TAstParseResult res = SqlToYql(R"(SELECT JSON_VALUE(NULL, "strict $.key");)");
  4520. UNIT_ASSERT(res.Root);
  4521. TVerifyLineFunc verifyLine = [&](const TString& word, const TString& line) {
  4522. Y_UNUSED(word);
  4523. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("(Nothing (OptionalType (DataType 'Json)))"));
  4524. };
  4525. TWordCountHive elementStat({"JsonValue"});
  4526. VerifyProgram(res, elementStat, verifyLine);
  4527. UNIT_ASSERT(elementStat["JsonValue"] > 0);
  4528. }
  4529. }
  4530. Y_UNIT_TEST_SUITE(JsonExists) {
  4531. Y_UNIT_TEST(JsonExistsValidHandlers) {
  4532. const TVector<std::pair<TString, TString>> testCases = {
  4533. {"", "(Just (Bool '\"false\"))"},
  4534. {"TRUE ON ERROR", "(Just (Bool '\"true\"))"},
  4535. {"FALSE ON ERROR", "(Just (Bool '\"false\"))"},
  4536. {"UNKNOWN ON ERROR", "(Nothing (OptionalType (DataType 'Bool)))"},
  4537. // NOTE: in this case we expect arguments of JsonExists callable to end immediately
  4538. // after variables. This parenthesis at the end of the expression is left on purpose
  4539. {"ERROR ON ERROR", "(Utf8 '\"strict $.key\") (JsonVariables))"},
  4540. };
  4541. for (const auto& item : testCases) {
  4542. NYql::TAstParseResult res = SqlToYql(
  4543. TStringBuilder() << R"(
  4544. $json = CAST(@@{"key": 1238}@@ as Json);
  4545. SELECT JSON_EXISTS($json, "strict $.key" )" << item.first << ");\n"
  4546. );
  4547. UNIT_ASSERT(res.Root);
  4548. TVerifyLineFunc verifyLine = [&](const TString& word, const TString& line) {
  4549. Y_UNUSED(word);
  4550. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(item.second));
  4551. };
  4552. TWordCountHive elementStat({"JsonExists"});
  4553. VerifyProgram(res, elementStat, verifyLine);
  4554. UNIT_ASSERT(elementStat["JsonExists"] > 0);
  4555. }
  4556. }
  4557. Y_UNIT_TEST(JsonExistsInvalidHandler) {
  4558. NYql::TAstParseResult res = SqlToYql(R"(
  4559. $json = CAST(@@{"key": 1238}@@ as Json);
  4560. $default = false;
  4561. SELECT JSON_EXISTS($json, "strict $.key" $default ON ERROR);
  4562. )");
  4563. UNIT_ASSERT(!res.Root);
  4564. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:4:53: Error: mismatched input '$' expecting {')', ERROR, FALSE, TRUE, UNKNOWN}\n");
  4565. }
  4566. Y_UNIT_TEST(JsonExistsNullInput) {
  4567. NYql::TAstParseResult res = SqlToYql(R"(SELECT JSON_EXISTS(NULL, "strict $.key");)");
  4568. UNIT_ASSERT(res.Root);
  4569. TVerifyLineFunc verifyLine = [&](const TString& word, const TString& line) {
  4570. Y_UNUSED(word);
  4571. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("(Nothing (OptionalType (DataType 'Json)))"));
  4572. };
  4573. TWordCountHive elementStat({"JsonExists"});
  4574. VerifyProgram(res, elementStat, verifyLine);
  4575. UNIT_ASSERT(elementStat["JsonExists"] > 0);
  4576. }
  4577. }
  4578. Y_UNIT_TEST_SUITE(JsonQuery) {
  4579. Y_UNIT_TEST(JsonQueryValidHandlers) {
  4580. using TTestSuite = const TVector<std::pair<TString, TString>>;
  4581. TTestSuite wrapCases = {
  4582. {"", "'NoWrap"},
  4583. {"WITHOUT WRAPPER", "'NoWrap"},
  4584. {"WITHOUT ARRAY WRAPPER", "'NoWrap"},
  4585. {"WITH WRAPPER", "'Wrap"},
  4586. {"WITH ARRAY WRAPPER", "'Wrap"},
  4587. {"WITH UNCONDITIONAL WRAPPER", "'Wrap"},
  4588. {"WITH UNCONDITIONAL ARRAY WRAPPER", "'Wrap"},
  4589. {"WITH CONDITIONAL WRAPPER", "'ConditionalWrap"},
  4590. {"WITH CONDITIONAL ARRAY WRAPPER", "'ConditionalWrap"},
  4591. };
  4592. TTestSuite handlerCases = {
  4593. {"", "'Null"},
  4594. {"ERROR", "'Error"},
  4595. {"NULL", "'Null"},
  4596. {"EMPTY ARRAY", "'EmptyArray"},
  4597. {"EMPTY OBJECT", "'EmptyObject"},
  4598. };
  4599. for (const auto& wrap : wrapCases) {
  4600. for (const auto& onError : handlerCases) {
  4601. for (const auto& onEmpty : handlerCases) {
  4602. TStringBuilder query;
  4603. query << R"($json = CAST(@@{"key": [123]}@@ as Json);
  4604. SELECT JSON_QUERY($json, "strict $.key" )" << wrap.first;
  4605. if (!onEmpty.first.empty()) {
  4606. if (wrap.first.StartsWith("WITH ")) {
  4607. continue;
  4608. }
  4609. query << " " << onEmpty.first << " ON EMPTY";
  4610. }
  4611. if (!onError.first.empty()) {
  4612. query << " " << onError.first << " ON ERROR";
  4613. }
  4614. query << ");\n";
  4615. NYql::TAstParseResult res = SqlToYql(query);
  4616. UNIT_ASSERT(res.Root);
  4617. TVerifyLineFunc verifyLine = [&](const TString& word, const TString& line) {
  4618. Y_UNUSED(word);
  4619. const TString args = TStringBuilder() << wrap.second << " " << onEmpty.second << " " << onError.second;
  4620. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(args));
  4621. };
  4622. Cout << wrap.first << " " << onEmpty.first << " " << onError.first << Endl;
  4623. TWordCountHive elementStat({"JsonQuery"});
  4624. VerifyProgram(res, elementStat, verifyLine);
  4625. UNIT_ASSERT(elementStat["JsonQuery"] > 0);
  4626. }
  4627. }
  4628. }
  4629. }
  4630. Y_UNIT_TEST(JsonQueryOnEmptyWithWrapper) {
  4631. NYql::TAstParseResult res = SqlToYql(R"(
  4632. $json = CAST(@@{"key": 1238}@@ as Json);
  4633. SELECT JSON_QUERY($json, "strict $" WITH ARRAY WRAPPER EMPTY ARRAY ON EMPTY);
  4634. )");
  4635. UNIT_ASSERT(!res.Root);
  4636. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:3:38: Error: ON EMPTY is prohibited because WRAPPER clause is specified\n");
  4637. }
  4638. Y_UNIT_TEST(JsonQueryNullInput) {
  4639. NYql::TAstParseResult res = SqlToYql(R"(SELECT JSON_QUERY(NULL, "strict $.key");)");
  4640. UNIT_ASSERT(res.Root);
  4641. TVerifyLineFunc verifyLine = [&](const TString& word, const TString& line) {
  4642. Y_UNUSED(word);
  4643. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("(Nothing (OptionalType (DataType 'Json)))"));
  4644. };
  4645. TWordCountHive elementStat({"JsonQuery"});
  4646. VerifyProgram(res, elementStat, verifyLine);
  4647. UNIT_ASSERT(elementStat["JsonQuery"] > 0);
  4648. }
  4649. }
  4650. Y_UNIT_TEST_SUITE(JsonPassing) {
  4651. Y_UNIT_TEST(SupportedVariableTypes) {
  4652. const TVector<TString> functions = {"JSON_EXISTS", "JSON_VALUE", "JSON_QUERY"};
  4653. for (const auto& function : functions) {
  4654. const auto query = Sprintf(R"(
  4655. pragma CompactNamedExprs;
  4656. $json = CAST(@@{"key": 1238}@@ as Json);
  4657. SELECT %s(
  4658. $json,
  4659. "strict $.key"
  4660. PASSING
  4661. "string" as var1,
  4662. 1.234 as var2,
  4663. CAST(1 as Int64) as var3,
  4664. true as var4,
  4665. $json as var5
  4666. ))",
  4667. function.data()
  4668. );
  4669. NYql::TAstParseResult res = SqlToYql(query);
  4670. UNIT_ASSERT(res.Root);
  4671. TVerifyLineFunc verifyLine = [&](const TString& word, const TString& line) {
  4672. Y_UNUSED(word);
  4673. UNIT_ASSERT_VALUES_UNEQUAL_C(TString::npos, line.find(R"('('"var1" (String '"string")))"), "Cannot find `var1`");
  4674. UNIT_ASSERT_VALUES_UNEQUAL_C(TString::npos, line.find(R"('('"var2" (Double '"1.234")))"), "Cannot find `var2`");
  4675. UNIT_ASSERT_VALUES_UNEQUAL_C(TString::npos, line.find(R"('('"var3" (SafeCast (Int32 '"1") (DataType 'Int64))))"), "Cannot find `var3`");
  4676. UNIT_ASSERT_VALUES_UNEQUAL_C(TString::npos, line.find(R"('('"var4" (Bool '"true")))"), "Cannot find `var4`");
  4677. UNIT_ASSERT_VALUES_UNEQUAL_C(TString::npos, line.find(R"('('"var5" namedexprnode0))"), "Cannot find `var5`");
  4678. };
  4679. TWordCountHive elementStat({"JsonVariables"});
  4680. VerifyProgram(res, elementStat, verifyLine);
  4681. UNIT_ASSERT(elementStat["JsonVariables"] > 0);
  4682. }
  4683. }
  4684. Y_UNIT_TEST(ValidVariableNames) {
  4685. const TVector<TString> functions = {"JSON_EXISTS", "JSON_VALUE", "JSON_QUERY"};
  4686. for (const auto& function : functions) {
  4687. const auto query = Sprintf(R"(
  4688. $json = CAST(@@{"key": 1238}@@ as Json);
  4689. SELECT %s(
  4690. $json,
  4691. "strict $.key"
  4692. PASSING
  4693. "one" as var1,
  4694. "two" as "VaR2",
  4695. "three" as `var3`,
  4696. "four" as VaR4
  4697. ))",
  4698. function.data()
  4699. );
  4700. NYql::TAstParseResult res = SqlToYql(query);
  4701. UNIT_ASSERT(res.Root);
  4702. TVerifyLineFunc verifyLine = [&](const TString& word, const TString& line) {
  4703. Y_UNUSED(word);
  4704. UNIT_ASSERT_VALUES_UNEQUAL_C(TString::npos, line.find(R"('('"var1" (String '"one")))"), "Cannot find `var1`");
  4705. UNIT_ASSERT_VALUES_UNEQUAL_C(TString::npos, line.find(R"('('"VaR2" (String '"two")))"), "Cannot find `VaR2`");
  4706. UNIT_ASSERT_VALUES_UNEQUAL_C(TString::npos, line.find(R"('('"var3" (String '"three")))"), "Cannot find `var3`");
  4707. UNIT_ASSERT_VALUES_UNEQUAL_C(TString::npos, line.find(R"('('"VaR4" (String '"four")))"), "Cannot find `VaR4`");
  4708. };
  4709. TWordCountHive elementStat({"JsonVariables"});
  4710. VerifyProgram(res, elementStat, verifyLine);
  4711. UNIT_ASSERT(elementStat["JsonVariables"] > 0);
  4712. }
  4713. }
  4714. }
  4715. Y_UNIT_TEST_SUITE(MigrationToJsonApi) {
  4716. Y_UNIT_TEST(WarningOnDeprecatedJsonUdf) {
  4717. NYql::TAstParseResult res = SqlToYql(R"(
  4718. $json = CAST(@@{"key": 1234}@@ as Json);
  4719. SELECT Json::Parse($json);
  4720. )");
  4721. UNIT_ASSERT(res.Root);
  4722. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:3:26: Warning: Json UDF is deprecated. Please use JSON API instead, code: 4506\n");
  4723. }
  4724. }
  4725. Y_UNIT_TEST_SUITE(AnsiIdentsNegative) {
  4726. Y_UNIT_TEST(EnableAnsiLexerFromRequestSpecialComments) {
  4727. auto req = "\n"
  4728. "\t --!ansi_lexer \n"
  4729. "-- Some comment\n"
  4730. "-- another comment\n"
  4731. "pragma SimpleColumns;\n"
  4732. "\n"
  4733. "select 1, '''' as empty;";
  4734. auto res = SqlToYql(req);
  4735. UNIT_ASSERT(res.IsOk());
  4736. UNIT_ASSERT(res.Issues.Size() == 0);
  4737. }
  4738. Y_UNIT_TEST(AnsiLexerShouldNotBeEnabledHere) {
  4739. auto req = "$str = '\n"
  4740. "--!ansi_lexer\n"
  4741. "--!syntax_v1\n"
  4742. "';\n"
  4743. "\n"
  4744. "select 1, $str, \"\" as empty;";
  4745. auto res = SqlToYql(req);
  4746. UNIT_ASSERT(res.IsOk());
  4747. UNIT_ASSERT(res.Issues.Size() == 0);
  4748. }
  4749. Y_UNIT_TEST(DoubleQuotesInDictsTuplesOrLists) {
  4750. auto req = "$d = { 'a': 1, \"b\": 2, 'c': 3,};";
  4751. auto res = SqlToYqlWithAnsiLexer(req);
  4752. UNIT_ASSERT(!res.Root);
  4753. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:16: Error: Column reference \"b\" is not allowed in current scope\n");
  4754. req = "$t = (1, 2, \"a\");";
  4755. res = SqlToYqlWithAnsiLexer(req);
  4756. UNIT_ASSERT(!res.Root);
  4757. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:13: Error: Column reference \"a\" is not allowed in current scope\n");
  4758. req = "$l = ['a', 'b', \"c\"];";
  4759. res = SqlToYqlWithAnsiLexer(req);
  4760. UNIT_ASSERT(!res.Root);
  4761. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:17: Error: Column reference \"c\" is not allowed in current scope\n");
  4762. }
  4763. Y_UNIT_TEST(MultilineComments) {
  4764. auto req = "/*/**/ select 1;";
  4765. auto res = SqlToYql(req);
  4766. UNIT_ASSERT(res.Root);
  4767. res = SqlToYqlWithAnsiLexer(req);
  4768. UNIT_ASSERT(res.IsOk());
  4769. UNIT_ASSERT(res.Issues.Size() == 0);
  4770. req = "/*\n"
  4771. "--/*\n"
  4772. "*/ select 1;";
  4773. res = SqlToYql(req);
  4774. UNIT_ASSERT(res.Root);
  4775. res = SqlToYqlWithAnsiLexer(req);
  4776. UNIT_ASSERT(res.IsOk());
  4777. UNIT_ASSERT(res.Issues.Size() == 0);
  4778. req = "/*\n"
  4779. "/*\n"
  4780. "--*/\n"
  4781. "*/ select 1;";
  4782. res = SqlToYql(req);
  4783. UNIT_ASSERT(!res.Root);
  4784. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:4:0: Error: mismatched input '*' expecting {';', '(', '$', ALTER, ANALYZE, BACKUP, COMMIT, CREATE, DECLARE, DEFINE, DELETE, DISCARD, DO, DROP, EVALUATE, EXPLAIN, EXPORT, FOR, FROM, GRANT, IF, IMPORT, INSERT, PARALLEL, PRAGMA, PROCESS, REDUCE, REPLACE, RESTORE, REVOKE, ROLLBACK, SELECT, UPDATE, UPSERT, USE, VALUES}\n");
  4785. res = SqlToYqlWithAnsiLexer(req);
  4786. UNIT_ASSERT(res.Root);
  4787. }
  4788. }
  4789. Y_UNIT_TEST_SUITE(AnsiOptionalAs) {
  4790. Y_UNIT_TEST(OptionalAsInProjection) {
  4791. UNIT_ASSERT(SqlToYql("PRAGMA AnsiOptionalAs; SELECT a b, c FROM plato.Input;").IsOk());
  4792. ExpectFailWithError("PRAGMA DisableAnsiOptionalAs;\n"
  4793. "SELECT a b, c FROM plato.Input;",
  4794. "<main>:2:10: Error: Expecting mandatory AS here. Did you miss comma? Please add PRAGMA AnsiOptionalAs; for ANSI compatibility\n");
  4795. }
  4796. Y_UNIT_TEST(OptionalAsWithKeywords) {
  4797. UNIT_ASSERT(SqlToYql("PRAGMA AnsiOptionalAs; SELECT a type, b data, c source FROM plato.Input;").IsOk());
  4798. }
  4799. }
  4800. Y_UNIT_TEST_SUITE(SessionWindowNegative) {
  4801. Y_UNIT_TEST(SessionWindowWithoutSource) {
  4802. ExpectFailWithError("SELECT 1 + SessionWindow(ts, 32);",
  4803. "<main>:1:12: Error: SessionWindow requires data source\n");
  4804. }
  4805. Y_UNIT_TEST(SessionWindowInProjection) {
  4806. ExpectFailWithError("SELECT 1 + SessionWindow(ts, 32) from plato.Input;",
  4807. "<main>:1:12: Error: SessionWindow can only be used as a top-level GROUP BY / PARTITION BY expression\n");
  4808. }
  4809. Y_UNIT_TEST(SessionWindowWithNonConstSecondArg) {
  4810. ExpectFailWithError(
  4811. "SELECT key, session_start FROM plato.Input\n"
  4812. "GROUP BY SessionWindow(ts, 32 + subkey) as session_start, key;",
  4813. "<main>:2:10: Error: Source does not allow column references\n"
  4814. "<main>:2:33: Error: Column reference 'subkey'\n");
  4815. }
  4816. Y_UNIT_TEST(SessionWindowWithWrongNumberOfArgs) {
  4817. ExpectFailWithError("SELECT * FROM plato.Input GROUP BY SessionWindow()",
  4818. "<main>:1:36: Error: SessionWindow requires either two or four arguments\n");
  4819. ExpectFailWithError("SELECT * FROM plato.Input GROUP BY SessionWindow(key, subkey, 100)",
  4820. "<main>:1:36: Error: SessionWindow requires either two or four arguments\n");
  4821. }
  4822. Y_UNIT_TEST(DuplicateSessionWindow) {
  4823. ExpectFailWithError(
  4824. "SELECT\n"
  4825. " *\n"
  4826. "FROM plato.Input\n"
  4827. "GROUP BY\n"
  4828. " SessionWindow(ts, 10),\n"
  4829. " user,\n"
  4830. " SessionWindow(ts, 20)\n"
  4831. ";",
  4832. "<main>:7:5: Error: Duplicate session window specification:\n"
  4833. "<main>:5:5: Error: Previous session window is declared here\n");
  4834. ExpectFailWithError(
  4835. "SELECT\n"
  4836. " MIN(key) over w\n"
  4837. "FROM plato.Input\n"
  4838. "WINDOW w AS (\n"
  4839. " PARTITION BY SessionWindow(ts, 10), user,\n"
  4840. " SessionWindow(ts, 20)\n"
  4841. ");",
  4842. "<main>:6:5: Error: Duplicate session window specification:\n"
  4843. "<main>:5:18: Error: Previous session window is declared here\n");
  4844. }
  4845. Y_UNIT_TEST(SessionStartStateWithoutSource) {
  4846. ExpectFailWithError("SELECT 1 + SessionStart();",
  4847. "<main>:1:12: Error: SessionStart requires data source\n");
  4848. ExpectFailWithError("SELECT 1 + SessionState();",
  4849. "<main>:1:12: Error: SessionState requires data source\n");
  4850. }
  4851. Y_UNIT_TEST(SessionStartStateWithoutGroupByOrWindow) {
  4852. ExpectFailWithError("SELECT 1 + SessionStart() from plato.Input;",
  4853. "<main>:1:12: Error: SessionStart can not be used without aggregation by SessionWindow\n");
  4854. ExpectFailWithError("SELECT 1 + SessionState() from plato.Input;",
  4855. "<main>:1:12: Error: SessionState can not be used without aggregation by SessionWindow\n");
  4856. }
  4857. Y_UNIT_TEST(SessionStartStateWithGroupByWithoutSession) {
  4858. ExpectFailWithError("SELECT 1 + SessionStart() from plato.Input group by user;",
  4859. "<main>:1:12: Error: SessionStart can not be used here: SessionWindow specification is missing in GROUP BY\n");
  4860. ExpectFailWithError("SELECT 1 + SessionState() from plato.Input group by user;",
  4861. "<main>:1:12: Error: SessionState can not be used here: SessionWindow specification is missing in GROUP BY\n");
  4862. }
  4863. Y_UNIT_TEST(SessionStartStateWithoutOverWithWindowWithoutSession) {
  4864. ExpectFailWithError("SELECT 1 + SessionStart(), MIN(key) over w from plato.Input window w as ()",
  4865. "<main>:1:12: Error: SessionStart can not be used without aggregation by SessionWindow. Maybe you forgot to add OVER `window_name`?\n");
  4866. ExpectFailWithError("SELECT 1 + SessionState(), MIN(key) over w from plato.Input window w as ()",
  4867. "<main>:1:12: Error: SessionState can not be used without aggregation by SessionWindow. Maybe you forgot to add OVER `window_name`?\n");
  4868. }
  4869. Y_UNIT_TEST(SessionStartStateWithWindowWithoutSession) {
  4870. ExpectFailWithError("SELECT 1 + SessionStart() over w, MIN(key) over w from plato.Input window w as ()",
  4871. "<main>:1:12: Error: SessionStart can not be used with window w: SessionWindow specification is missing in PARTITION BY\n");
  4872. ExpectFailWithError("SELECT 1 + SessionState() over w, MIN(key) over w from plato.Input window w as ()",
  4873. "<main>:1:12: Error: SessionState can not be used with window w: SessionWindow specification is missing in PARTITION BY\n");
  4874. }
  4875. Y_UNIT_TEST(SessionStartStateWithSessionedWindow) {
  4876. ExpectFailWithError("SELECT 1 + SessionStart(), MIN(key) over w from plato.Input group by key window w as (partition by SessionWindow(ts, 1)) ",
  4877. "<main>:1:12: Error: SessionStart can not be used here: SessionWindow specification is missing in GROUP BY. Maybe you forgot to add OVER `window_name`?\n");
  4878. ExpectFailWithError("SELECT 1 + SessionState(), MIN(key) over w from plato.Input group by key window w as (partition by SessionWindow(ts, 1)) ",
  4879. "<main>:1:12: Error: SessionState can not be used here: SessionWindow specification is missing in GROUP BY. Maybe you forgot to add OVER `window_name`?\n");
  4880. }
  4881. Y_UNIT_TEST(AggregationBySessionStateIsNotSupportedYet) {
  4882. ExpectFailWithError("SELECT SOME(1 + SessionState()), key from plato.Input group by key, SessionWindow(ts, 1);",
  4883. "<main>:1:17: Error: SessionState with GROUP BY is not supported yet\n");
  4884. }
  4885. Y_UNIT_TEST(SessionWindowInRtmr) {
  4886. NYql::TAstParseResult res = SqlToYql(
  4887. "SELECT * FROM plato.Input GROUP BY SessionWindow(ts, 10);",
  4888. 10, TString(NYql::RtmrProviderName));
  4889. UNIT_ASSERT(!res.Root);
  4890. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:1:54: Error: Streaming group by query must have a hopping window specification.\n");
  4891. res = SqlToYql(R"(
  4892. SELECT key, SUM(value) AS value FROM plato.Input
  4893. GROUP BY key, HOP(subkey, "PT10S", "PT30S", "PT20S"), SessionWindow(ts, 10);
  4894. )", 10, TString(NYql::RtmrProviderName));
  4895. UNIT_ASSERT(!res.Root);
  4896. UNIT_ASSERT_NO_DIFF(Err2Str(res), "<main>:2:13: Error: SessionWindow is unsupported for streaming sources\n");
  4897. }
  4898. }
  4899. Y_UNIT_TEST_SUITE(LibraSqlSugar) {
  4900. auto makeResult = [](TStringBuf settings) {
  4901. return SqlToYql(
  4902. TStringBuilder()
  4903. << settings
  4904. << "\n$udf1 = MyLibra::MakeLibraPreprocessor($settings);"
  4905. << "\n$udf2 = CustomLibra::MakeLibraPreprocessor($settings);"
  4906. << "\nPROCESS plato.Input USING $udf1(TableRow())"
  4907. << "\nUNION ALL"
  4908. << "\nPROCESS plato.Input USING $udf2(TableRow());"
  4909. );
  4910. };
  4911. Y_UNIT_TEST(EmptySettings) {
  4912. auto res = makeResult(R"(
  4913. $settings = AsStruct();
  4914. )");
  4915. UNIT_ASSERT(res.IsOk());
  4916. }
  4917. Y_UNIT_TEST(OnlyEntities) {
  4918. auto res = makeResult(R"(
  4919. $settings = AsStruct(
  4920. AsList("A", "B", "C") AS Entities
  4921. );
  4922. )");
  4923. UNIT_ASSERT(res.IsOk());
  4924. }
  4925. Y_UNIT_TEST(EntitiesWithStrategy) {
  4926. auto res = makeResult(R"(
  4927. $settings = AsStruct(
  4928. AsList("A", "B", "C") AS Entities,
  4929. "blacklist" AS EntitiesStrategy
  4930. );
  4931. )");
  4932. UNIT_ASSERT(res.IsOk());
  4933. }
  4934. Y_UNIT_TEST(AllSettings) {
  4935. auto res = makeResult(R"(
  4936. $settings = AsStruct(
  4937. AsList("A", "B", "C") AS Entities,
  4938. "whitelist" AS EntitiesStrategy,
  4939. "path" AS BlockstatDict,
  4940. false AS ParseWithFat,
  4941. "map" AS Mode
  4942. );
  4943. )");
  4944. UNIT_ASSERT(res.IsOk());
  4945. }
  4946. Y_UNIT_TEST(BadStrategy) {
  4947. auto res = makeResult(R"(
  4948. $settings = AsStruct("bad" AS EntitiesStrategy);
  4949. )");
  4950. UNIT_ASSERT_STRING_CONTAINS(
  4951. Err2Str(res),
  4952. "Error: MakeLibraPreprocessor got invalid entities strategy: expected 'whitelist' or 'blacklist'"
  4953. );
  4954. }
  4955. Y_UNIT_TEST(BadEntities) {
  4956. auto res = makeResult(R"(
  4957. $settings = AsStruct(AsList("A", 1) AS Entities);
  4958. )");
  4959. UNIT_ASSERT_STRING_CONTAINS(Err2Str(res), "Error: MakeLibraPreprocessor entity must be string literal");
  4960. }
  4961. }
  4962. Y_UNIT_TEST_SUITE(TrailingQuestionsNegative) {
  4963. Y_UNIT_TEST(Basic) {
  4964. ExpectFailWithError("SELECT 1?;", "<main>:1:9: Error: Unexpected token '?' at the end of expression\n");
  4965. ExpectFailWithError("SELECT 1? + 1;", "<main>:1:10: Error: mismatched input '+' expecting {<EOF>, ';'}\n");
  4966. ExpectFailWithError("SELECT 1 + 1??? < 2", "<main>:1:13: Error: Unexpected token '?' at the end of expression\n");
  4967. ExpectFailWithError("SELECT 1? > 2? > 3?",
  4968. "<main>:1:11: Error: Unexpected token '?' at the end of expression\n"
  4969. "<main>:1:16: Error: Unexpected token '?' at the end of expression\n"
  4970. "<main>:1:21: Error: Unexpected token '?' at the end of expression\n");
  4971. }
  4972. Y_UNIT_TEST(SmartParen) {
  4973. ExpectFailWithError("$x = 1; SELECT (Int32?, $x?)", "<main>:1:27: Error: Unexpected token '?' at the end of expression\n");
  4974. ExpectFailWithError("SELECT (Int32, foo?)", "<main>:1:19: Error: Unexpected token '?' at the end of expression\n");
  4975. }
  4976. Y_UNIT_TEST(LambdaOptArgs) {
  4977. ExpectFailWithError("$l = ($x, $y?, $z??, $t?) -> ($x);", "<main>:1:18: Error: Expecting at most one '?' token here (for optional lambda parameters), but got 2\n");
  4978. }
  4979. }
  4980. Y_UNIT_TEST_SUITE(FlexibleTypes) {
  4981. Y_UNIT_TEST(AssumeOrderByType) {
  4982. UNIT_ASSERT(SqlToYql("PRAGMA FlexibleTypes; SELECT 1 AS int32 ASSUME ORDER BY int32").IsOk());
  4983. }
  4984. Y_UNIT_TEST(GroupingSets) {
  4985. UNIT_ASSERT(SqlToYql("PRAGMA FlexibleTypes; SELECT COUNT(*) AS cnt, text, uuid FROM plato.Input GROUP BY GROUPING SETS((uuid), (uuid, text));").IsOk());
  4986. }
  4987. Y_UNIT_TEST(WeakField) {
  4988. UNIT_ASSERT(SqlToYql("PRAGMA FlexibleTypes; SELECT WeakField(text, string) as text FROM plato.Input").IsOk());
  4989. }
  4990. Y_UNIT_TEST(Aggregation1) {
  4991. TString q =
  4992. "PRAGMA FlexibleTypes;\n"
  4993. "$foo = ($x, $const, $type) -> ($x || $const || FormatType($type));\n"
  4994. "SELECT $foo(SOME(x), 'aaa', String) FROM plato.Input GROUP BY y;";
  4995. UNIT_ASSERT(SqlToYql(q).IsOk());
  4996. }
  4997. Y_UNIT_TEST(Aggregation2) {
  4998. TString q =
  4999. "PRAGMA FlexibleTypes;\n"
  5000. "SELECT 1 + String + MAX(key) FROM plato.Input;";
  5001. UNIT_ASSERT(SqlToYql(q).IsOk());
  5002. }
  5003. }
  5004. Y_UNIT_TEST_SUITE(ExternalDeclares) {
  5005. Y_UNIT_TEST(BasicUsage) {
  5006. NSQLTranslation::TTranslationSettings settings;
  5007. settings.DeclaredNamedExprs["foo"] = "String";
  5008. auto res = SqlToYqlWithSettings("select $foo;", settings);
  5009. UNIT_ASSERT(res.IsOk());
  5010. UNIT_ASSERT(res.Issues.Size() == 0);
  5011. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  5012. if (word == "declare") {
  5013. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(R"__((declare "$foo" (DataType 'String)))__"));
  5014. }
  5015. };
  5016. TWordCountHive elementStat = {{TString("declare"), 0}};
  5017. VerifyProgram(res, elementStat, verifyLine);
  5018. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["declare"]);
  5019. }
  5020. Y_UNIT_TEST(DeclareOverrides) {
  5021. NSQLTranslation::TTranslationSettings settings;
  5022. settings.DeclaredNamedExprs["foo"] = "String";
  5023. auto res = SqlToYqlWithSettings("declare $foo as Int32; select $foo;", settings);
  5024. UNIT_ASSERT(res.IsOk());
  5025. UNIT_ASSERT(res.Issues.Size() == 0);
  5026. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  5027. if (word == "declare") {
  5028. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(R"__((declare "$foo" (DataType 'Int32)))__"));
  5029. }
  5030. };
  5031. TWordCountHive elementStat = {{TString("declare"), 0}};
  5032. VerifyProgram(res, elementStat, verifyLine);
  5033. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["declare"]);
  5034. }
  5035. Y_UNIT_TEST(UnusedDeclareDoesNotProduceWarning) {
  5036. NSQLTranslation::TTranslationSettings settings;
  5037. settings.DeclaredNamedExprs["foo"] = "String";
  5038. auto res = SqlToYqlWithSettings("select 1;", settings);
  5039. UNIT_ASSERT(res.IsOk());
  5040. UNIT_ASSERT(res.Issues.Size() == 0);
  5041. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  5042. if (word == "declare") {
  5043. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(R"__((declare "$foo" (DataType 'String)))__"));
  5044. }
  5045. };
  5046. TWordCountHive elementStat = {{TString("declare"), 0}};
  5047. VerifyProgram(res, elementStat, verifyLine);
  5048. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["declare"]);
  5049. }
  5050. Y_UNIT_TEST(DeclaresWithInvalidTypesFails) {
  5051. NSQLTranslation::TTranslationSettings settings;
  5052. settings.DeclaredNamedExprs["foo"] = "List<BadType>";
  5053. auto res = SqlToYqlWithSettings("select 1;", settings);
  5054. UNIT_ASSERT(!res.Root);
  5055. UNIT_ASSERT_NO_DIFF(Err2Str(res),
  5056. "<main>:0:5: Error: Unknown type: 'BadType'\n"
  5057. "<main>: Error: Failed to parse type for externally declared name 'foo'\n");
  5058. }
  5059. }
  5060. Y_UNIT_TEST_SUITE(ExternalDataSource) {
  5061. Y_UNIT_TEST(CreateExternalDataSourceWithAuthNone) {
  5062. NYql::TAstParseResult res = SqlToYql(R"sql(
  5063. USE plato;
  5064. CREATE EXTERNAL DATA SOURCE MyDataSource WITH (
  5065. SOURCE_TYPE="ObjectStorage",
  5066. LOCATION="my-bucket",
  5067. AUTH_METHOD="NONE"
  5068. );
  5069. )sql");
  5070. UNIT_ASSERT(res.Root);
  5071. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  5072. if (word == "Write") {
  5073. UNIT_ASSERT_STRING_CONTAINS(line, R"#('('('"auth_method" '"NONE") '('"location" '"my-bucket") '('"source_type" '"ObjectStorage"))#");
  5074. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("createObject"));
  5075. }
  5076. };
  5077. TWordCountHive elementStat = { {TString("Write"), 0} };
  5078. VerifyProgram(res, elementStat, verifyLine);
  5079. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  5080. }
  5081. Y_UNIT_TEST(CreateExternalDataSourceWithAuthServiceAccount) {
  5082. NYql::TAstParseResult res = SqlToYql(R"sql(
  5083. USE plato;
  5084. CREATE EXTERNAL DATA SOURCE MyDataSource WITH (
  5085. SOURCE_TYPE="ObjectStorage",
  5086. LOCATION="my-bucket",
  5087. AUTH_METHOD="SERVICE_ACCOUNT",
  5088. SERVICE_ACCOUNT_ID="sa",
  5089. SERVICE_ACCOUNT_SECRET_NAME="sa_secret_name"
  5090. );
  5091. )sql");
  5092. UNIT_ASSERT(res.Root);
  5093. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  5094. if (word == "Write") {
  5095. UNIT_ASSERT_STRING_CONTAINS(line, R"#('('('"auth_method" '"SERVICE_ACCOUNT") '('"location" '"my-bucket") '('"service_account_id" '"sa") '('"service_account_secret_name" '"sa_secret_name") '('"source_type" '"ObjectStorage"))#");
  5096. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("createObject"));
  5097. }
  5098. };
  5099. TWordCountHive elementStat = { {TString("Write"), 0} };
  5100. VerifyProgram(res, elementStat, verifyLine);
  5101. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  5102. }
  5103. Y_UNIT_TEST(CreateExternalDataSourceWithBasic) {
  5104. NYql::TAstParseResult res = SqlToYql(R"sql(
  5105. USE plato;
  5106. CREATE EXTERNAL DATA SOURCE MyDataSource WITH (
  5107. SOURCE_TYPE="PostgreSQL",
  5108. LOCATION="protocol://host:port/",
  5109. AUTH_METHOD="BASIC",
  5110. LOGIN="admin",
  5111. PASSWORD_SECRET_NAME="secret_name"
  5112. );
  5113. )sql");
  5114. UNIT_ASSERT(res.Root);
  5115. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  5116. if (word == "Write") {
  5117. UNIT_ASSERT_STRING_CONTAINS(line, R"#('('('"auth_method" '"BASIC") '('"location" '"protocol://host:port/") '('"login" '"admin") '('"password_secret_name" '"secret_name") '('"source_type" '"PostgreSQL"))#");
  5118. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("createObject"));
  5119. }
  5120. };
  5121. TWordCountHive elementStat = { {TString("Write"), 0} };
  5122. VerifyProgram(res, elementStat, verifyLine);
  5123. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  5124. }
  5125. Y_UNIT_TEST(CreateExternalDataSourceWithMdbBasic) {
  5126. NYql::TAstParseResult res = SqlToYql(R"sql(
  5127. USE plato;
  5128. CREATE EXTERNAL DATA SOURCE MyDataSource WITH (
  5129. SOURCE_TYPE="PostgreSQL",
  5130. LOCATION="protocol://host:port/",
  5131. AUTH_METHOD="MDB_BASIC",
  5132. SERVICE_ACCOUNT_ID="sa",
  5133. SERVICE_ACCOUNT_SECRET_NAME="sa_secret_name",
  5134. LOGIN="admin",
  5135. PASSWORD_SECRET_NAME="secret_name"
  5136. );
  5137. )sql");
  5138. UNIT_ASSERT(res.Root);
  5139. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  5140. if (word == "Write") {
  5141. UNIT_ASSERT_STRING_CONTAINS(line, R"#('('('"auth_method" '"MDB_BASIC") '('"location" '"protocol://host:port/") '('"login" '"admin") '('"password_secret_name" '"secret_name") '('"service_account_id" '"sa") '('"service_account_secret_name" '"sa_secret_name") '('"source_type" '"PostgreSQL"))#");
  5142. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("createObject"));
  5143. }
  5144. };
  5145. TWordCountHive elementStat = { {TString("Write"), 0} };
  5146. VerifyProgram(res, elementStat, verifyLine);
  5147. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  5148. }
  5149. Y_UNIT_TEST(CreateExternalDataSourceWithAws) {
  5150. NYql::TAstParseResult res = SqlToYql(R"sql(
  5151. USE plato;
  5152. CREATE EXTERNAL DATA SOURCE MyDataSource WITH (
  5153. SOURCE_TYPE="PostgreSQL",
  5154. LOCATION="protocol://host:port/",
  5155. AUTH_METHOD="AWS",
  5156. AWS_ACCESS_KEY_ID_SECRET_NAME="secred_id_name",
  5157. AWS_SECRET_ACCESS_KEY_SECRET_NAME="secret_key_name",
  5158. AWS_REGION="ru-central-1"
  5159. );
  5160. )sql");
  5161. UNIT_ASSERT(res.Root);
  5162. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  5163. if (word == "Write") {
  5164. UNIT_ASSERT_STRING_CONTAINS(line, R"#('('('"auth_method" '"AWS") '('"aws_access_key_id_secret_name" '"secred_id_name") '('"aws_region" '"ru-central-1") '('"aws_secret_access_key_secret_name" '"secret_key_name") '('"location" '"protocol://host:port/") '('"source_type" '"PostgreSQL"))#");
  5165. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("createObject"));
  5166. }
  5167. };
  5168. TWordCountHive elementStat = { {TString("Write"), 0} };
  5169. VerifyProgram(res, elementStat, verifyLine);
  5170. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  5171. }
  5172. Y_UNIT_TEST(CreateExternalDataSourceWithToken) {
  5173. NYql::TAstParseResult res = SqlToYql(R"sql(
  5174. USE plato;
  5175. CREATE EXTERNAL DATA SOURCE MyDataSource WITH (
  5176. SOURCE_TYPE="YT",
  5177. LOCATION="protocol://host:port/",
  5178. AUTH_METHOD="TOKEN",
  5179. TOKEN_SECRET_NAME="token_name"
  5180. );
  5181. )sql");
  5182. UNIT_ASSERT(res.Root);
  5183. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  5184. if (word == "Write") {
  5185. UNIT_ASSERT_STRING_CONTAINS(line, R"#('('('"auth_method" '"TOKEN") '('"location" '"protocol://host:port/") '('"source_type" '"YT") '('"token_secret_name" '"token_name"))#");
  5186. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("createObject"));
  5187. }
  5188. };
  5189. TWordCountHive elementStat = { {TString("Write"), 0} };
  5190. VerifyProgram(res, elementStat, verifyLine);
  5191. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  5192. }
  5193. Y_UNIT_TEST(CreateExternalDataSourceWithTablePrefix) {
  5194. NYql::TAstParseResult res = SqlToYql(R"sql(
  5195. USE plato;
  5196. pragma TablePathPrefix='/aba';
  5197. CREATE EXTERNAL DATA SOURCE MyDataSource WITH (
  5198. SOURCE_TYPE="ObjectStorage",
  5199. LOCATION="my-bucket",
  5200. AUTH_METHOD="NONE"
  5201. );
  5202. )sql");
  5203. UNIT_ASSERT(res.Root);
  5204. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  5205. if (word == "Write") {
  5206. UNIT_ASSERT_STRING_CONTAINS(line, "/aba/MyDataSource");
  5207. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("createObject"));
  5208. }
  5209. };
  5210. TWordCountHive elementStat = { {TString("Write"), 0} };
  5211. VerifyProgram(res, elementStat, verifyLine);
  5212. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  5213. }
  5214. Y_UNIT_TEST(CreateExternalDataSourceIfNotExists) {
  5215. NYql::TAstParseResult res = SqlToYql(R"sql(
  5216. USE plato;
  5217. CREATE EXTERNAL DATA SOURCE IF NOT EXISTS MyDataSource WITH (
  5218. SOURCE_TYPE="ObjectStorage",
  5219. LOCATION="my-bucket",
  5220. AUTH_METHOD="NONE"
  5221. );
  5222. )sql");
  5223. UNIT_ASSERT(res.Root);
  5224. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  5225. if (word == "Write") {
  5226. UNIT_ASSERT_STRING_CONTAINS(line, R"#('('('"auth_method" '"NONE") '('"location" '"my-bucket") '('"source_type" '"ObjectStorage"))#");
  5227. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("createObjectIfNotExists"));
  5228. }
  5229. };
  5230. TWordCountHive elementStat = { {TString("Write"), 0} };
  5231. VerifyProgram(res, elementStat, verifyLine);
  5232. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  5233. }
  5234. Y_UNIT_TEST(AlterExternalDataSource) {
  5235. NYql::TAstParseResult res = SqlToYql(R"sql(
  5236. USE plato;
  5237. ALTER EXTERNAL DATA SOURCE MyDataSource
  5238. SET (SOURCE_TYPE = "ObjectStorage", Login = "Admin"),
  5239. SET Location "bucket",
  5240. RESET (Auth_Method, Service_Account_Id, Service_Account_Secret_Name);
  5241. )sql");
  5242. UNIT_ASSERT_C(res.Root, res.Issues.ToString());
  5243. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  5244. if (word == "Write") {
  5245. UNIT_ASSERT_STRING_CONTAINS(line, R"#(('mode 'alterObject))#");
  5246. UNIT_ASSERT_STRING_CONTAINS(line, R"#('('features '('('"location" '"bucket") '('"login" '"Admin") '('"source_type" '"ObjectStorage"))))#");
  5247. UNIT_ASSERT_STRING_CONTAINS(line, R"#('('resetFeatures '('"auth_method" '"service_account_id" '"service_account_secret_name")))#");
  5248. }
  5249. };
  5250. TWordCountHive elementStat = { {TString("Write"), 0} };
  5251. VerifyProgram(res, elementStat, verifyLine);
  5252. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  5253. }
  5254. Y_UNIT_TEST(CreateExternalDataSourceOrReplace) {
  5255. NYql::TAstParseResult res = SqlToYql(R"(
  5256. USE plato;
  5257. CREATE OR REPLACE EXTERNAL DATA SOURCE MyDataSource WITH (
  5258. SOURCE_TYPE="ObjectStorage",
  5259. LOCATION="my-bucket",
  5260. AUTH_METHOD="NONE"
  5261. );
  5262. )");
  5263. UNIT_ASSERT(res.Root);
  5264. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  5265. if (word == "Write") {
  5266. UNIT_ASSERT_STRING_CONTAINS(line, R"#('('('"auth_method" '"NONE") '('"location" '"my-bucket") '('"source_type" '"ObjectStorage"))#");
  5267. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("createObjectOrReplace"));
  5268. }
  5269. };
  5270. TWordCountHive elementStat = { {TString("Write"), 0} };
  5271. VerifyProgram(res, elementStat, verifyLine);
  5272. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  5273. }
  5274. Y_UNIT_TEST(CreateOrReplaceForUnsupportedTableTypesShouldFail) {
  5275. ExpectFailWithError(R"sql(
  5276. USE plato;
  5277. CREATE OR REPLACE TABLE t (a int32 not null, primary key(a, a));
  5278. )sql" , "<main>:3:23: Error: OR REPLACE feature is supported only for EXTERNAL DATA SOURCE and EXTERNAL TABLE\n");
  5279. ExpectFailWithError(R"sql(
  5280. USE plato;
  5281. CREATE OR REPLACE TABLE t (
  5282. Key Uint64,
  5283. Value1 String,
  5284. PRIMARY KEY (Key)
  5285. )
  5286. WITH (
  5287. STORE = COLUMN,
  5288. AUTO_PARTITIONING_MIN_PARTITIONS_COUNT = 10
  5289. );
  5290. )sql" , "<main>:3:23: Error: OR REPLACE feature is supported only for EXTERNAL DATA SOURCE and EXTERNAL TABLE\n");
  5291. }
  5292. Y_UNIT_TEST(CreateExternalDataSourceWithBadArguments) {
  5293. ExpectFailWithError(R"sql(
  5294. USE plato;
  5295. CREATE EXTERNAL DATA SOURCE MyDataSource;
  5296. )sql" , "<main>:3:56: Error: mismatched input ';' expecting WITH\n");
  5297. ExpectFailWithError(R"sql(
  5298. USE plato;
  5299. CREATE EXTERNAL DATA SOURCE MyDataSource WITH (
  5300. LOCATION="my-bucket",
  5301. AUTH_METHOD="NONE"
  5302. );
  5303. )sql" , "<main>:5:33: Error: SOURCE_TYPE requires key\n");
  5304. ExpectFailWithError(R"sql(
  5305. USE plato;
  5306. CREATE EXTERNAL DATA SOURCE MyDataSource WITH (
  5307. SOURCE_TYPE="ObjectStorage",
  5308. LOCATION="my-bucket"
  5309. );
  5310. )sql" , "<main>:5:30: Error: AUTH_METHOD requires key\n");
  5311. ExpectFailWithError(R"sql(
  5312. USE plato;
  5313. CREATE EXTERNAL DATA SOURCE MyDataSource WITH (
  5314. SOURCE_TYPE="ObjectStorage",
  5315. LOCATION="my-bucket",
  5316. AUTH_METHOD="NONE1"
  5317. );
  5318. )sql" , "<main>:6:33: Error: Unknown AUTH_METHOD = NONE1\n");
  5319. ExpectFailWithError(R"sql(
  5320. USE plato;
  5321. CREATE EXTERNAL DATA SOURCE MyDataSource WITH (
  5322. SOURCE_TYPE="ObjectStorage",
  5323. LOCATION="my-bucket",
  5324. AUTH_METHOD="SERVICE_ACCOUNT"
  5325. );
  5326. )sql" , "<main>:6:33: Error: SERVICE_ACCOUNT_ID requires key\n");
  5327. ExpectFailWithError(R"sql(
  5328. USE plato;
  5329. CREATE EXTERNAL DATA SOURCE MyDataSource WITH (
  5330. SOURCE_TYPE="ObjectStorage",
  5331. LOCATION="my-bucket",
  5332. AUTH_METHOD="SERVICE_ACCOUNT",
  5333. SERVICE_ACCOUNT_ID="s1"
  5334. );
  5335. )sql" , "<main>:7:40: Error: SERVICE_ACCOUNT_SECRET_NAME requires key\n");
  5336. ExpectFailWithError(R"sql(
  5337. USE plato;
  5338. CREATE EXTERNAL DATA SOURCE MyDataSource WITH (
  5339. SOURCE_TYPE="ObjectStorage",
  5340. LOCATION="my-bucket",
  5341. AUTH_METHOD="SERVICE_ACCOUNT",
  5342. SERVICE_ACCOUNT_SECRET_NAME="s1"
  5343. );
  5344. )sql" , "<main>:7:49: Error: SERVICE_ACCOUNT_ID requires key\n");
  5345. ExpectFailWithError(R"sql(
  5346. USE plato;
  5347. CREATE EXTERNAL DATA SOURCE MyDataSource WITH (
  5348. SOURCE_TYPE="PostgreSQL",
  5349. LOCATION="protocol://host:port/",
  5350. AUTH_METHOD="BASIC",
  5351. LOGIN="admin"
  5352. );
  5353. )sql" , "<main>:7:27: Error: PASSWORD_SECRET_NAME requires key\n");
  5354. ExpectFailWithError(R"sql(
  5355. USE plato;
  5356. CREATE EXTERNAL DATA SOURCE MyDataSource WITH (
  5357. SOURCE_TYPE="PostgreSQL",
  5358. LOCATION="protocol://host:port/",
  5359. AUTH_METHOD="BASIC",
  5360. PASSWORD_SECRET_NAME="secret_name"
  5361. );
  5362. )sql" , "<main>:7:42: Error: LOGIN requires key\n");
  5363. ExpectFailWithError(R"sql(
  5364. USE plato;
  5365. CREATE EXTERNAL DATA SOURCE MyDataSource WITH (
  5366. SOURCE_TYPE="PostgreSQL",
  5367. LOCATION="protocol://host:port/",
  5368. AUTH_METHOD="MDB_BASIC",
  5369. SERVICE_ACCOUNT_SECRET_NAME="sa_secret_name",
  5370. LOGIN="admin",
  5371. PASSWORD_SECRET_NAME="secret_name"
  5372. );
  5373. )sql" , "<main>:9:42: Error: SERVICE_ACCOUNT_ID requires key\n");
  5374. ExpectFailWithError(R"sql(
  5375. USE plato;
  5376. CREATE EXTERNAL DATA SOURCE MyDataSource WITH (
  5377. SOURCE_TYPE="PostgreSQL",
  5378. LOCATION="protocol://host:port/",
  5379. AUTH_METHOD="MDB_BASIC",
  5380. SERVICE_ACCOUNT_ID="sa",
  5381. LOGIN="admin",
  5382. PASSWORD_SECRET_NAME="secret_name"
  5383. );
  5384. )sql" , "<main>:9:42: Error: SERVICE_ACCOUNT_SECRET_NAME requires key\n");
  5385. ExpectFailWithError(R"sql(
  5386. USE plato;
  5387. CREATE EXTERNAL DATA SOURCE MyDataSource WITH (
  5388. SOURCE_TYPE="PostgreSQL",
  5389. LOCATION="protocol://host:port/",
  5390. AUTH_METHOD="MDB_BASIC",
  5391. SERVICE_ACCOUNT_ID="sa",
  5392. SERVICE_ACCOUNT_SECRET_NAME="sa_secret_name",
  5393. PASSWORD_SECRET_NAME="secret_name"
  5394. );
  5395. )sql" , "<main>:9:42: Error: LOGIN requires key\n");
  5396. ExpectFailWithError(R"sql(
  5397. USE plato;
  5398. CREATE EXTERNAL DATA SOURCE MyDataSource WITH (
  5399. SOURCE_TYPE="PostgreSQL",
  5400. LOCATION="protocol://host:port/",
  5401. AUTH_METHOD="MDB_BASIC",
  5402. SERVICE_ACCOUNT_ID="sa",
  5403. SERVICE_ACCOUNT_SECRET_NAME="sa_secret_name",
  5404. LOGIN="admin"
  5405. );
  5406. )sql" , "<main>:9:27: Error: PASSWORD_SECRET_NAME requires key\n");
  5407. ExpectFailWithError(R"sql(
  5408. USE plato;
  5409. CREATE EXTERNAL DATA SOURCE MyDataSource WITH (
  5410. SOURCE_TYPE="PostgreSQL",
  5411. LOCATION="protocol://host:port/",
  5412. AUTH_METHOD="AWS",
  5413. AWS_SECRET_ACCESS_KEY_SECRET_NAME="secret_key_name",
  5414. AWS_REGION="ru-central-1"
  5415. );
  5416. )sql" , "<main>:8:32: Error: AWS_ACCESS_KEY_ID_SECRET_NAME requires key\n");
  5417. ExpectFailWithError(R"sql(
  5418. USE plato;
  5419. CREATE EXTERNAL DATA SOURCE MyDataSource WITH (
  5420. SOURCE_TYPE="PostgreSQL",
  5421. LOCATION="protocol://host:port/",
  5422. AUTH_METHOD="AWS",
  5423. AWS_ACCESS_KEY_ID_SECRET_NAME="secred_id_name",
  5424. AWS_REGION="ru-central-1"
  5425. );
  5426. )sql" , "<main>:8:32: Error: AWS_SECRET_ACCESS_KEY_SECRET_NAME requires key\n");
  5427. ExpectFailWithError(R"sql(
  5428. USE plato;
  5429. CREATE EXTERNAL DATA SOURCE MyDataSource WITH (
  5430. SOURCE_TYPE="PostgreSQL",
  5431. LOCATION="protocol://host:port/",
  5432. AUTH_METHOD="AWS",
  5433. AWS_SECRET_ACCESS_KEY_SECRET_NAME="secret_key_name",
  5434. AWS_ACCESS_KEY_ID_SECRET_NAME="secred_id_name"
  5435. );
  5436. )sql" , "<main>:8:51: Error: AWS_REGION requires key\n");
  5437. }
  5438. Y_UNIT_TEST(DropExternalDataSourceWithTablePrefix) {
  5439. NYql::TAstParseResult res = SqlToYql(R"sql(
  5440. USE plato;
  5441. DROP EXTERNAL DATA SOURCE MyDataSource;
  5442. )sql");
  5443. UNIT_ASSERT(res.Root);
  5444. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  5445. if (word == "Write") {
  5446. UNIT_ASSERT_VALUES_EQUAL(TString::npos, line.find("'features"));
  5447. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("dropObject"));
  5448. }
  5449. };
  5450. TWordCountHive elementStat = { {TString("Write"), 0}};
  5451. VerifyProgram(res, elementStat, verifyLine);
  5452. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  5453. }
  5454. Y_UNIT_TEST(DropExternalDataSource) {
  5455. NYql::TAstParseResult res = SqlToYql(R"sql(
  5456. USE plato;
  5457. pragma TablePathPrefix='/aba';
  5458. DROP EXTERNAL DATA SOURCE MyDataSource;
  5459. )sql");
  5460. UNIT_ASSERT(res.Root);
  5461. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  5462. if (word == "Write") {
  5463. UNIT_ASSERT_STRING_CONTAINS(line, "/aba/MyDataSource");
  5464. UNIT_ASSERT_VALUES_EQUAL(TString::npos, line.find("'features"));
  5465. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("dropObject"));
  5466. }
  5467. };
  5468. TWordCountHive elementStat = { {TString("Write"), 0}};
  5469. VerifyProgram(res, elementStat, verifyLine);
  5470. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  5471. }
  5472. Y_UNIT_TEST(DropExternalDataSourceIfExists) {
  5473. NYql::TAstParseResult res = SqlToYql(R"sql(
  5474. USE plato;
  5475. DROP EXTERNAL DATA SOURCE IF EXISTS MyDataSource;
  5476. )sql");
  5477. UNIT_ASSERT(res.Root);
  5478. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  5479. if (word == "Write") {
  5480. UNIT_ASSERT_STRING_CONTAINS(line, "MyDataSource");
  5481. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("dropObjectIfExists"));
  5482. }
  5483. };
  5484. TWordCountHive elementStat = { {TString("Write"), 0}};
  5485. VerifyProgram(res, elementStat, verifyLine);
  5486. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  5487. }
  5488. }
  5489. Y_UNIT_TEST_SUITE(ExternalTable) {
  5490. Y_UNIT_TEST(CreateExternalTable) {
  5491. NYql::TAstParseResult res = SqlToYql(R"sql(
  5492. USE plato;
  5493. CREATE EXTERNAL TABLE mytable (
  5494. a int
  5495. ) WITH (
  5496. DATA_SOURCE="/Root/mydatasource",
  5497. LOCATION="/folder1/*"
  5498. );
  5499. )sql");
  5500. UNIT_ASSERT_C(res.Root, res.Issues.ToOneLineString());
  5501. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  5502. if (word == "Write") {
  5503. UNIT_ASSERT_STRING_CONTAINS(line, R"#('('('data_source_path (String '"/Root/mydatasource")) '('location (String '"/folder1/*")))) '('tableType 'externalTable)))))#");
  5504. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("tablescheme"));
  5505. }
  5506. };
  5507. TWordCountHive elementStat = { {TString("Write"), 0} };
  5508. VerifyProgram(res, elementStat, verifyLine);
  5509. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  5510. }
  5511. Y_UNIT_TEST(CreateExternalTableWithTablePrefix) {
  5512. NYql::TAstParseResult res = SqlToYql(R"sql(
  5513. USE plato;
  5514. pragma TablePathPrefix='/aba';
  5515. CREATE EXTERNAL TABLE mytable (
  5516. a int
  5517. ) WITH (
  5518. DATA_SOURCE="mydatasource",
  5519. LOCATION="/folder1/*"
  5520. );
  5521. )sql");
  5522. UNIT_ASSERT_C(res.Root, res.Issues.ToOneLineString());
  5523. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  5524. if (word == "Write") {
  5525. UNIT_ASSERT_STRING_CONTAINS(line, "/aba/mydatasource");
  5526. UNIT_ASSERT_STRING_CONTAINS(line, "/aba/mytable");
  5527. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("tablescheme"));
  5528. }
  5529. };
  5530. TWordCountHive elementStat = { {TString("Write"), 0} };
  5531. VerifyProgram(res, elementStat, verifyLine);
  5532. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  5533. }
  5534. Y_UNIT_TEST(CreateExternalTableObjectStorage) {
  5535. auto res = SqlToYql(R"sql(
  5536. USE plato;
  5537. CREATE EXTERNAL TABLE mytable (
  5538. a int,
  5539. year Int
  5540. ) WITH (
  5541. DATA_SOURCE="/Root/mydatasource",
  5542. LOCATION="/folder1/*",
  5543. FORMAT="json_as_string",
  5544. `projection.enabled`="true",
  5545. `projection.year.type`="integer",
  5546. `projection.year.min`="2010",
  5547. `projection.year.max`="2022",
  5548. `projection.year.interval`="1",
  5549. `projection.month.type`="integer",
  5550. `projection.month.min`="1",
  5551. `projection.month.max`="12",
  5552. `projection.month.interval`="1",
  5553. `projection.month.digits`="2",
  5554. `storage.location.template`="${year}/${month}",
  5555. PARTITONED_BY = "[year, month]"
  5556. );
  5557. )sql");
  5558. UNIT_ASSERT_C(res.IsOk(), res.Issues.ToString());
  5559. }
  5560. Y_UNIT_TEST(CreateExternalTableIfNotExists) {
  5561. NYql::TAstParseResult res = SqlToYql(R"sql(
  5562. USE plato;
  5563. CREATE EXTERNAL TABLE IF NOT EXISTS mytable (
  5564. a int
  5565. ) WITH (
  5566. DATA_SOURCE="/Root/mydatasource",
  5567. LOCATION="/folder1/*"
  5568. );
  5569. )sql");
  5570. UNIT_ASSERT_C(res.Root, res.Issues.ToOneLineString());
  5571. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  5572. if (word == "Write") {
  5573. UNIT_ASSERT_STRING_CONTAINS(line, R"#('('('data_source_path (String '"/Root/mydatasource")) '('location (String '"/folder1/*")))) '('tableType 'externalTable)))))#");
  5574. UNIT_ASSERT_STRING_CONTAINS(line, "create_if_not_exists");
  5575. }
  5576. };
  5577. TWordCountHive elementStat = { {TString("Write"), 0} };
  5578. VerifyProgram(res, elementStat, verifyLine);
  5579. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  5580. }
  5581. Y_UNIT_TEST(CreateExternalTableOrReplace) {
  5582. NYql::TAstParseResult res = SqlToYql(R"(
  5583. USE plato;
  5584. CREATE OR REPLACE EXTERNAL TABLE mytable (
  5585. a int
  5586. ) WITH (
  5587. DATA_SOURCE="/Root/mydatasource",
  5588. LOCATION="/folder1/*"
  5589. );
  5590. )");
  5591. UNIT_ASSERT_C(res.Root, res.Issues.ToOneLineString());
  5592. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  5593. if (word == "Write") {
  5594. UNIT_ASSERT_STRING_CONTAINS(line, R"#('('('data_source_path (String '"/Root/mydatasource")) '('location (String '"/folder1/*")))) '('tableType 'externalTable)))))#");
  5595. UNIT_ASSERT_STRING_CONTAINS(line, "create_or_replace");
  5596. }
  5597. };
  5598. TWordCountHive elementStat = { {TString("Write"), 0} };
  5599. VerifyProgram(res, elementStat, verifyLine);
  5600. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  5601. }
  5602. Y_UNIT_TEST(AlterExternalTableAddColumn) {
  5603. NYql::TAstParseResult res = SqlToYql(R"sql(
  5604. USE plato;
  5605. ALTER EXTERNAL TABLE mytable
  5606. ADD COLUMN my_column int32,
  5607. RESET (LOCATION);
  5608. )sql");
  5609. UNIT_ASSERT_C(res.Root, res.Issues.ToOneLineString());
  5610. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  5611. if (word == "Write") {
  5612. UNIT_ASSERT_STRING_CONTAINS(line, R"#('actions '('('addColumns '('('"my_column" (AsOptionalType (DataType 'Int32))#");
  5613. UNIT_ASSERT_STRING_CONTAINS(line, R"#(('setTableSettings '('('location)))#");
  5614. UNIT_ASSERT_STRING_CONTAINS(line, R"#(('tableType 'externalTable))#");
  5615. UNIT_ASSERT_STRING_CONTAINS(line, R"#(('mode 'alter))#");
  5616. }
  5617. };
  5618. TWordCountHive elementStat = { {TString("Write"), 0} };
  5619. VerifyProgram(res, elementStat, verifyLine);
  5620. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  5621. }
  5622. Y_UNIT_TEST(AlterExternalTableDropColumn) {
  5623. NYql::TAstParseResult res = SqlToYql(R"sql(
  5624. USE plato;
  5625. ALTER EXTERNAL TABLE mytable
  5626. DROP COLUMN my_column,
  5627. SET (Location = "abc", Other_Prop = "42"),
  5628. SET x 'y';
  5629. )sql");
  5630. UNIT_ASSERT_C(res.Root, res.Issues.ToOneLineString());
  5631. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  5632. if (word == "Write") {
  5633. UNIT_ASSERT_STRING_CONTAINS(line, R"#('actions '('('dropColumns '('"my_column")#");
  5634. UNIT_ASSERT_STRING_CONTAINS(line, R"#(('setTableSettings '('('location (String '"abc")) '('Other_Prop (String '"42")) '('x (String '"y")))))#");
  5635. UNIT_ASSERT_STRING_CONTAINS(line, R"#(('tableType 'externalTable))#");
  5636. UNIT_ASSERT_STRING_CONTAINS(line, R"#(('mode 'alter))#");
  5637. }
  5638. };
  5639. TWordCountHive elementStat = { {TString("Write"), 0} };
  5640. VerifyProgram(res, elementStat, verifyLine);
  5641. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  5642. }
  5643. Y_UNIT_TEST(CreateExternalTableWithBadArguments) {
  5644. ExpectFailWithError(R"sql(
  5645. USE plato;
  5646. CREATE EXTERNAL TABLE mytable;
  5647. )sql" , "<main>:3:45: Error: mismatched input ';' expecting '('\n");
  5648. ExpectFailWithError(R"sql(
  5649. USE plato;
  5650. CREATE EXTERNAL TABLE mytable (
  5651. a int
  5652. );
  5653. )sql" , "<main>:4:23: Error: DATA_SOURCE requires key\n");
  5654. ExpectFailWithError(R"sql(
  5655. USE plato;
  5656. CREATE EXTERNAL TABLE mytable (
  5657. a int
  5658. ) WITH (
  5659. DATA_SOURCE="/Root/mydatasource"
  5660. );
  5661. )sql" , "<main>:6:33: Error: LOCATION requires key\n");
  5662. ExpectFailWithError(R"sql(
  5663. USE plato;
  5664. CREATE EXTERNAL TABLE mytable (
  5665. a int
  5666. ) WITH (
  5667. LOCATION="/folder1/*"
  5668. );
  5669. )sql" , "<main>:6:30: Error: DATA_SOURCE requires key\n");
  5670. ExpectFailWithError(R"sql(
  5671. USE plato;
  5672. CREATE EXTERNAL TABLE mytable (
  5673. a int,
  5674. PRIMARY KEY(a)
  5675. ) WITH (
  5676. DATA_SOURCE="/Root/mydatasource",
  5677. LOCATION="/folder1/*"
  5678. );
  5679. )sql" , "<main>:8:30: Error: PRIMARY KEY is not supported for external table\n");
  5680. }
  5681. Y_UNIT_TEST(DropExternalTable) {
  5682. NYql::TAstParseResult res = SqlToYql(R"sql(
  5683. USE plato;
  5684. DROP EXTERNAL TABLE MyExternalTable;
  5685. )sql");
  5686. UNIT_ASSERT(res.Root);
  5687. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  5688. if (word == "Write") {
  5689. UNIT_ASSERT_VALUES_EQUAL(TString::npos, line.find("tablescheme"));
  5690. }
  5691. };
  5692. TWordCountHive elementStat = { {TString("Write"), 0}};
  5693. VerifyProgram(res, elementStat, verifyLine);
  5694. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  5695. }
  5696. Y_UNIT_TEST(DropExternalTableWithTablePrefix) {
  5697. NYql::TAstParseResult res = SqlToYql(R"sql(
  5698. USE plato;
  5699. pragma TablePathPrefix='/aba';
  5700. DROP EXTERNAL TABLE MyExternalTable;
  5701. )sql");
  5702. UNIT_ASSERT(res.Root);
  5703. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  5704. if (word == "Write") {
  5705. UNIT_ASSERT_STRING_CONTAINS(line, "/aba/MyExternalTable");
  5706. UNIT_ASSERT_VALUES_EQUAL(TString::npos, line.find("'tablescheme"));
  5707. }
  5708. };
  5709. TWordCountHive elementStat = { {TString("Write"), 0}};
  5710. VerifyProgram(res, elementStat, verifyLine);
  5711. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  5712. }
  5713. Y_UNIT_TEST(DropExternalTableIfExists) {
  5714. NYql::TAstParseResult res = SqlToYql(R"sql(
  5715. USE plato;
  5716. DROP EXTERNAL TABLE IF EXISTS MyExternalTable;
  5717. )sql");
  5718. UNIT_ASSERT(res.Root);
  5719. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  5720. if (word == "Write") {
  5721. UNIT_ASSERT_VALUES_EQUAL(TString::npos, line.find("tablescheme"));
  5722. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("drop_if_exists"));
  5723. }
  5724. };
  5725. TWordCountHive elementStat = { {TString("Write"), 0}};
  5726. VerifyProgram(res, elementStat, verifyLine);
  5727. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  5728. }
  5729. }
  5730. Y_UNIT_TEST_SUITE(TopicsDDL) {
  5731. void TestQuery(const TString& query, bool expectOk = true) {
  5732. TStringBuilder finalQuery;
  5733. finalQuery << "use plato;" << Endl << query;
  5734. auto res = SqlToYql(finalQuery, 10, "kikimr");
  5735. if (expectOk) {
  5736. UNIT_ASSERT_C(res.IsOk(), res.Issues.ToString());
  5737. } else {
  5738. UNIT_ASSERT(!res.IsOk());
  5739. }
  5740. }
  5741. Y_UNIT_TEST(CreateTopicSimple) {
  5742. TestQuery(R"(
  5743. CREATE TOPIC topic1;
  5744. )");
  5745. TestQuery(R"(
  5746. CREATE TOPIC `cluster1.topic1`;
  5747. )");
  5748. TestQuery(R"(
  5749. CREATE TOPIC topic1 WITH (metering_mode = "str_value", partition_count_limit = 123, retention_period = Interval('PT1H'));
  5750. )");
  5751. }
  5752. Y_UNIT_TEST(CreateTopicConsumer) {
  5753. TestQuery(R"(
  5754. CREATE TOPIC topic1 (CONSUMER cons1);
  5755. )");
  5756. TestQuery(R"(
  5757. CREATE TOPIC topic1 (CONSUMER cons1, CONSUMER cons2 WITH (important = false));
  5758. )");
  5759. TestQuery(R"(
  5760. CREATE TOPIC topic1 (CONSUMER cons1, CONSUMER cons2 WITH (important = false)) WITH (supported_codecs = "1,2,3");
  5761. )");
  5762. }
  5763. Y_UNIT_TEST(AlterTopicSimple) {
  5764. TestQuery(R"(
  5765. ALTER TOPIC topic1 SET (retention_period = Interval('PT1H'));
  5766. )");
  5767. TestQuery(R"(
  5768. ALTER TOPIC topic1 SET (retention_storage_mb = 3, partition_count_limit = 50);
  5769. )");
  5770. TestQuery(R"(
  5771. ALTER TOPIC topic1 RESET (supported_codecs, retention_period);
  5772. )");
  5773. TestQuery(R"(
  5774. ALTER TOPIC topic1 RESET (partition_write_speed_bytes_per_second),
  5775. SET (partition_write_burst_bytes = 11111, min_active_partitions = 1);
  5776. )");
  5777. }
  5778. Y_UNIT_TEST(AlterTopicConsumer) {
  5779. TestQuery(R"(
  5780. ALTER TOPIC topic1 ADD CONSUMER consumer1,
  5781. ADD CONSUMER consumer2 WITH (important = false, supported_codecs = "RAW"),
  5782. ALTER CONSUMER consumer3 SET (important = false, read_from = 1),
  5783. ALTER CONSUMER consumer3 RESET (supported_codecs),
  5784. DROP CONSUMER consumer4,
  5785. SET (partition_count_limit = 11, retention_period = Interval('PT1H')),
  5786. RESET(metering_mode)
  5787. )");
  5788. }
  5789. Y_UNIT_TEST(DropTopic) {
  5790. TestQuery(R"(
  5791. DROP TOPIC topic1;
  5792. )");
  5793. }
  5794. Y_UNIT_TEST(TopicBadRequests) {
  5795. TestQuery(R"(
  5796. CREATE TOPIC topic1();
  5797. )", false);
  5798. TestQuery(R"(
  5799. CREATE TOPIC topic1 SET setting1 = value1;
  5800. )", false);
  5801. TestQuery(R"(
  5802. ALTER TOPIC topic1 SET setting1 value1;
  5803. )", false);
  5804. TestQuery(R"(
  5805. ALTER TOPIC topic1 RESET setting1;
  5806. )", false);
  5807. TestQuery(R"(
  5808. ALTER TOPIC topic1 DROP CONSUMER consumer4 WITH (k1 = v1);
  5809. )", false);
  5810. TestQuery(R"(
  5811. CREATE TOPIC topic1 WITH (retention_period = 123);
  5812. )", false);
  5813. TestQuery(R"(
  5814. CREATE TOPIC topic1 (CONSUMER cons1, CONSUMER cons1 WITH (important = false));
  5815. )", false);
  5816. TestQuery(R"(
  5817. CREATE TOPIC topic1 (CONSUMER cons1 WITH (bad_option = false));
  5818. )", false);
  5819. TestQuery(R"(
  5820. ALTER TOPIC topic1 ADD CONSUMER cons1, ALTER CONSUMER cons1 RESET (important);
  5821. )", false);
  5822. TestQuery(R"(
  5823. ALTER TOPIC topic1 ADD CONSUMER consumer1,
  5824. ALTER CONSUMER consumer3 SET (supported_codecs = "RAW", read_from = 1),
  5825. ALTER CONSUMER consumer3 RESET (supported_codecs);
  5826. )", false);
  5827. TestQuery(R"(
  5828. ALTER TOPIC topic1 ADD CONSUMER consumer1,
  5829. ALTER CONSUMER consumer3 SET (supported_codecs = "RAW", read_from = 1),
  5830. ALTER CONSUMER consumer3 SET (read_from = 2);
  5831. )", false);
  5832. }
  5833. Y_UNIT_TEST(TopicWithPrefix) {
  5834. NYql::TAstParseResult res = SqlToYql(R"(
  5835. USE plato;
  5836. PRAGMA TablePathPrefix = '/database/path/to/tables';
  5837. ALTER TOPIC `my_table/my_feed` ADD CONSUMER `my_consumer`;
  5838. )");
  5839. UNIT_ASSERT(res.Root);
  5840. TWordCountHive elementStat = {{TString("/database/path/to/tables/my_table/my_feed"), 0}, {"topic", 0}};
  5841. VerifyProgram(res, elementStat);
  5842. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["topic"]);
  5843. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["/database/path/to/tables/my_table/my_feed"]);
  5844. }
  5845. }
  5846. Y_UNIT_TEST_SUITE(BlockEnginePragma) {
  5847. Y_UNIT_TEST(Basic) {
  5848. const TVector<TString> values = {"auto", "force", "disable"};
  5849. for (const auto& value : values) {
  5850. const auto query = TStringBuilder() << "pragma Blockengine='" << value << "'; select 1;";
  5851. NYql::TAstParseResult res = SqlToYql(query);
  5852. UNIT_ASSERT(res.Root);
  5853. TVerifyLineFunc verifyLine = [&](const TString& word, const TString& line) {
  5854. Y_UNUSED(word);
  5855. UNIT_ASSERT_STRING_CONTAINS(line, TStringBuilder() << R"(Configure! world (DataSource '"config") '"BlockEngine" '")" << value << "\"");
  5856. };
  5857. TWordCountHive elementStat({"BlockEngine"});
  5858. VerifyProgram(res, elementStat, verifyLine);
  5859. UNIT_ASSERT(elementStat["BlockEngine"] == ((value == "disable") ? 0 : 1));
  5860. }
  5861. }
  5862. Y_UNIT_TEST(UnknownSetting) {
  5863. ExpectFailWithError("use plato; pragma BlockEngine='foo';",
  5864. "<main>:1:31: Error: Expected `disable|auto|force' argument for: BlockEngine\n");
  5865. }
  5866. }
  5867. Y_UNIT_TEST_SUITE(TViewSyntaxTest) {
  5868. Y_UNIT_TEST(CreateViewSimple) {
  5869. NYql::TAstParseResult res = SqlToYql(R"(
  5870. USE plato;
  5871. CREATE VIEW TheView WITH (security_invoker = TRUE) AS SELECT 1;
  5872. )"
  5873. );
  5874. UNIT_ASSERT_C(res.Root, res.Issues.ToString());
  5875. }
  5876. Y_UNIT_TEST(CreateViewIfNotExists) {
  5877. constexpr const char* name = "TheView";
  5878. NYql::TAstParseResult res = SqlToYql(std::format(R"(
  5879. USE plato;
  5880. CREATE VIEW IF NOT EXISTS {} AS SELECT 1;
  5881. )", name
  5882. ));
  5883. UNIT_ASSERT_C(res.Root, res.Issues.ToString());
  5884. TVerifyLineFunc verifyLine = [&](const TString& word, const TString& line) {
  5885. if (word == "Write!") {
  5886. UNIT_ASSERT_STRING_CONTAINS(line, name);
  5887. UNIT_ASSERT_STRING_CONTAINS(line, "createObjectIfNotExists");
  5888. }
  5889. };
  5890. TWordCountHive elementStat = { {"Write!"} };
  5891. VerifyProgram(res, elementStat, verifyLine);
  5892. UNIT_ASSERT_VALUES_EQUAL(elementStat["Write!"], 1);
  5893. }
  5894. Y_UNIT_TEST(CreateViewFromTable) {
  5895. constexpr const char* path = "/PathPrefix/TheView";
  5896. constexpr const char* query = R"(
  5897. SELECT * FROM SomeTable
  5898. )";
  5899. NYql::TAstParseResult res = SqlToYql(std::format(R"(
  5900. USE plato;
  5901. CREATE VIEW `{}` WITH (security_invoker = TRUE) AS {};
  5902. )",
  5903. path,
  5904. query
  5905. )
  5906. );
  5907. UNIT_ASSERT_C(res.Root, res.Issues.ToString());
  5908. TVerifyLineFunc verifyLine = [&](const TString& word, const TString& line) {
  5909. if (word == "Write!") {
  5910. UNIT_ASSERT_STRING_CONTAINS(line, path);
  5911. UNIT_ASSERT_STRING_CONTAINS(line, "createObject");
  5912. }
  5913. };
  5914. TWordCountHive elementStat = { {"Write!"} };
  5915. VerifyProgram(res, elementStat, verifyLine);
  5916. UNIT_ASSERT_VALUES_EQUAL(elementStat["Write!"], 1);
  5917. }
  5918. Y_UNIT_TEST(CheckReconstructedQuery) {
  5919. constexpr const char* path = "/PathPrefix/TheView";
  5920. constexpr const char* query = R"(
  5921. SELECT * FROM FirstTable JOIN SecondTable ON FirstTable.key == SecondTable.key
  5922. )";
  5923. NYql::TAstParseResult res = SqlToYql(std::format(R"(
  5924. USE plato;
  5925. CREATE VIEW `{}` WITH (security_invoker = TRUE) AS {};
  5926. )",
  5927. path,
  5928. query
  5929. )
  5930. );
  5931. UNIT_ASSERT_C(res.Root, res.Issues.ToString());
  5932. TString reconstructedQuery = ToString(Tokenize(query));
  5933. TVerifyLineFunc verifyLine = [&](const TString& word, const TString& line) {
  5934. if (word == "query_text") {
  5935. UNIT_ASSERT_STRING_CONTAINS(line, reconstructedQuery);
  5936. }
  5937. };
  5938. TWordCountHive elementStat = { {"Write!"} };
  5939. VerifyProgram(res, elementStat, verifyLine);
  5940. UNIT_ASSERT_VALUES_EQUAL(elementStat["Write!"], 1);
  5941. }
  5942. Y_UNIT_TEST(DropView) {
  5943. constexpr const char* path = "/PathPrefix/TheView";
  5944. NYql::TAstParseResult res = SqlToYql(std::format(R"(
  5945. USE plato;
  5946. DROP VIEW `{}`;
  5947. )",
  5948. path
  5949. )
  5950. );
  5951. UNIT_ASSERT_C(res.Root, res.Issues.ToString());
  5952. TVerifyLineFunc verifyLine = [&](const TString& word, const TString& line) {
  5953. if (word == "Write!") {
  5954. UNIT_ASSERT_STRING_CONTAINS(line, path);
  5955. UNIT_ASSERT_STRING_CONTAINS(line, "dropObject");
  5956. }
  5957. };
  5958. TWordCountHive elementStat = { {"Write!"} };
  5959. VerifyProgram(res, elementStat, verifyLine);
  5960. UNIT_ASSERT_VALUES_EQUAL(elementStat["Write!"], 1);
  5961. }
  5962. Y_UNIT_TEST(DropViewIfExists) {
  5963. constexpr const char* name = "TheView";
  5964. NYql::TAstParseResult res = SqlToYql(std::format(R"(
  5965. USE plato;
  5966. DROP VIEW IF EXISTS {};
  5967. )", name
  5968. ));
  5969. UNIT_ASSERT_C(res.Root, res.Issues.ToString());
  5970. TVerifyLineFunc verifyLine = [&](const TString& word, const TString& line) {
  5971. if (word == "Write!") {
  5972. UNIT_ASSERT_STRING_CONTAINS(line, name);
  5973. UNIT_ASSERT_STRING_CONTAINS(line, "dropObjectIfExists");
  5974. }
  5975. };
  5976. TWordCountHive elementStat = { {"Write!"} };
  5977. VerifyProgram(res, elementStat, verifyLine);
  5978. UNIT_ASSERT_VALUES_EQUAL(elementStat["Write!"], 1);
  5979. }
  5980. Y_UNIT_TEST(CreateViewWithTablePrefix) {
  5981. NYql::TAstParseResult res = SqlToYql(R"(
  5982. USE plato;
  5983. PRAGMA TablePathPrefix='/PathPrefix';
  5984. CREATE VIEW TheView WITH (security_invoker = TRUE) AS SELECT 1;
  5985. )"
  5986. );
  5987. UNIT_ASSERT_C(res.Root, res.Issues.ToString());
  5988. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  5989. if (word == "Write!") {
  5990. UNIT_ASSERT_STRING_CONTAINS(line, "/PathPrefix/TheView");
  5991. UNIT_ASSERT_STRING_CONTAINS(line, "createObject");
  5992. }
  5993. };
  5994. TWordCountHive elementStat = { {"Write!"} };
  5995. VerifyProgram(res, elementStat, verifyLine);
  5996. UNIT_ASSERT_VALUES_EQUAL(elementStat["Write!"], 1);
  5997. }
  5998. Y_UNIT_TEST(DropViewWithTablePrefix) {
  5999. NYql::TAstParseResult res = SqlToYql(R"(
  6000. USE plato;
  6001. PRAGMA TablePathPrefix='/PathPrefix';
  6002. DROP VIEW TheView;
  6003. )"
  6004. );
  6005. UNIT_ASSERT_C(res.Root, res.Issues.ToString());
  6006. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  6007. if (word == "Write") {
  6008. UNIT_ASSERT_STRING_CONTAINS(line, "/PathPrefix/TheView");
  6009. UNIT_ASSERT_STRING_CONTAINS(line, "dropObject");
  6010. }
  6011. };
  6012. TWordCountHive elementStat = { {"Write!"} };
  6013. VerifyProgram(res, elementStat, verifyLine);
  6014. UNIT_ASSERT_VALUES_EQUAL(elementStat["Write!"], 1);
  6015. }
  6016. Y_UNIT_TEST(YtAlternativeSchemaSyntax) {
  6017. NYql::TAstParseResult res = SqlToYql(R"(
  6018. SELECT * FROM plato.Input WITH schema(y Int32, x String not null);
  6019. )");
  6020. UNIT_ASSERT_C(res.Root, res.Issues.ToString());
  6021. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  6022. if (word == "userschema") {
  6023. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos,
  6024. line.find(R"__('('('"userschema" (StructType '('"y" (AsOptionalType (DataType 'Int32))) '('"x" (DataType 'String))))))__"));
  6025. }
  6026. };
  6027. TWordCountHive elementStat = {{TString("userschema"), 0}};
  6028. VerifyProgram(res, elementStat, verifyLine);
  6029. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["userschema"]);
  6030. }
  6031. Y_UNIT_TEST(UseViewAndFullColumnId) {
  6032. NYql::TAstParseResult res = SqlToYql("USE plato; SELECT Input.x FROM Input VIEW uitzicht;");
  6033. UNIT_ASSERT(res.Root);
  6034. TWordCountHive elementStat = {{TString("SqlAccess"), 0}, {"SqlProjectItem", 0}, {"Read!", 0}};
  6035. VerifyProgram(res, elementStat);
  6036. UNIT_ASSERT_VALUES_EQUAL(0, elementStat["SqlAccess"]);
  6037. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["SqlProjectItem"]);
  6038. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Read!"]);
  6039. }
  6040. }
  6041. Y_UNIT_TEST_SUITE(CompactNamedExprs) {
  6042. Y_UNIT_TEST(SourceCallablesInWrongContext) {
  6043. TString query = R"(
  6044. pragma CompactNamedExprs;
  6045. $foo = %s();
  6046. select $foo from plato.Input;
  6047. )";
  6048. THashMap<TString, TString> errs = {
  6049. {"TableRow", "<main>:3:20: Error: TableRow requires data source\n"},
  6050. {"JoinTableRow", "<main>:3:20: Error: JoinTableRow requires data source\n"},
  6051. {"TableRecordIndex", "<main>:3:20: Error: Unable to use function: TableRecord without source\n"},
  6052. {"TablePath", "<main>:3:20: Error: Unable to use function: TablePath without source\n"},
  6053. {"SystemMetadata", "<main>:3:20: Error: Unable to use function: SystemMetadata without source\n"},
  6054. };
  6055. for (TString callable : { "TableRow", "JoinTableRow", "TableRecordIndex", "TablePath", "SystemMetadata"}) {
  6056. auto req = Sprintf(query.c_str(), callable.c_str());
  6057. ExpectFailWithError(req, errs[callable]);
  6058. }
  6059. }
  6060. Y_UNIT_TEST(ValidateUnusedExprs) {
  6061. TString query = R"(
  6062. pragma warning("disable", "4527");
  6063. pragma CompactNamedExprs;
  6064. pragma ValidateUnusedExprs;
  6065. $foo = count(1);
  6066. select 1;
  6067. )";
  6068. ExpectFailWithError(query, "<main>:6:20: Error: Aggregation is not allowed in this context\n");
  6069. query = R"(
  6070. pragma warning("disable", "4527");
  6071. pragma CompactNamedExprs;
  6072. pragma ValidateUnusedExprs;
  6073. define subquery $x() as
  6074. select count(1, 2);
  6075. end define;
  6076. select 1;
  6077. )";
  6078. ExpectFailWithError(query, "<main>:7:24: Error: Aggregation function Count requires exactly 1 argument(s), given: 2\n");
  6079. }
  6080. Y_UNIT_TEST(DisableValidateUnusedExprs) {
  6081. TString query = R"(
  6082. pragma warning("disable", "4527");
  6083. pragma CompactNamedExprs;
  6084. pragma DisableValidateUnusedExprs;
  6085. $foo = count(1);
  6086. select 1;
  6087. )";
  6088. SqlToYql(query).IsOk();
  6089. query = R"(
  6090. pragma warning("disable", "4527");
  6091. pragma CompactNamedExprs;
  6092. pragma DisableValidateUnusedExprs;
  6093. define subquery $x() as
  6094. select count(1, 2);
  6095. end define;
  6096. select 1;
  6097. )";
  6098. SqlToYql(query).IsOk();
  6099. }
  6100. }
  6101. Y_UNIT_TEST_SUITE(ResourcePool) {
  6102. Y_UNIT_TEST(CreateResourcePool) {
  6103. NYql::TAstParseResult res = SqlToYql(R"sql(
  6104. USE plato;
  6105. CREATE RESOURCE POOL MyResourcePool WITH (
  6106. CONCURRENT_QUERY_LIMIT=20,
  6107. QUERY_CANCEL_AFTER_SECONDS=86400,
  6108. QUEUE_TYPE="FIFO"
  6109. );
  6110. )sql");
  6111. UNIT_ASSERT_C(res.Root, res.Issues.ToString());
  6112. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  6113. if (word == "Write") {
  6114. UNIT_ASSERT_STRING_CONTAINS(line, R"#('('('"concurrent_query_limit" (Int32 '"20")) '('"query_cancel_after_seconds" (Int32 '"86400")) '('"queue_type" '"FIFO"))#");
  6115. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("createObject"));
  6116. }
  6117. };
  6118. TWordCountHive elementStat = { {TString("Write"), 0} };
  6119. VerifyProgram(res, elementStat, verifyLine);
  6120. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  6121. }
  6122. Y_UNIT_TEST(CreateResourcePoolWithBadArguments) {
  6123. ExpectFailWithError(R"sql(
  6124. USE plato;
  6125. CREATE RESOURCE POOL MyResourcePool;
  6126. )sql" , "<main>:3:51: Error: mismatched input ';' expecting WITH\n");
  6127. ExpectFailWithError(R"sql(
  6128. USE plato;
  6129. CREATE RESOURCE POOL MyResourcePool WITH (
  6130. DUPLICATE_SETTING="first_value",
  6131. DUPLICATE_SETTING="second_value"
  6132. );
  6133. )sql" , "<main>:5:21: Error: DUPLICATE_SETTING duplicate keys\n");
  6134. }
  6135. Y_UNIT_TEST(AlterResourcePool) {
  6136. NYql::TAstParseResult res = SqlToYql(R"sql(
  6137. USE plato;
  6138. ALTER RESOURCE POOL MyResourcePool
  6139. SET (CONCURRENT_QUERY_LIMIT = 30, Weight = 5, QUEUE_TYPE = "UNORDERED"),
  6140. RESET (Query_Cancel_After_Seconds, Query_Count_Limit);
  6141. )sql");
  6142. UNIT_ASSERT_C(res.Root, res.Issues.ToString());
  6143. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  6144. if (word == "Write") {
  6145. UNIT_ASSERT_STRING_CONTAINS(line, R"#(('mode 'alterObject))#");
  6146. UNIT_ASSERT_STRING_CONTAINS(line, R"#('('features '('('"concurrent_query_limit" (Int32 '"30")) '('"queue_type" '"UNORDERED") '('"weight" (Int32 '"5")))))#");
  6147. UNIT_ASSERT_STRING_CONTAINS(line, R"#('('resetFeatures '('"query_cancel_after_seconds" '"query_count_limit")))#");
  6148. }
  6149. };
  6150. TWordCountHive elementStat = { {TString("Write"), 0} };
  6151. VerifyProgram(res, elementStat, verifyLine);
  6152. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  6153. }
  6154. Y_UNIT_TEST(DropResourcePool) {
  6155. NYql::TAstParseResult res = SqlToYql(R"sql(
  6156. USE plato;
  6157. DROP RESOURCE POOL MyResourcePool;
  6158. )sql");
  6159. UNIT_ASSERT(res.Root);
  6160. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  6161. if (word == "Write") {
  6162. UNIT_ASSERT_VALUES_EQUAL(TString::npos, line.find("'features"));
  6163. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("dropObject"));
  6164. }
  6165. };
  6166. TWordCountHive elementStat = { {TString("Write"), 0}};
  6167. VerifyProgram(res, elementStat, verifyLine);
  6168. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  6169. }
  6170. }
  6171. Y_UNIT_TEST_SUITE(BackupCollection) {
  6172. Y_UNIT_TEST(CreateBackupCollection) {
  6173. NYql::TAstParseResult res = SqlToYql(R"sql(
  6174. USE plato;
  6175. CREATE BACKUP COLLECTION TestCollection WITH (
  6176. STORAGE="local",
  6177. TAG="test" -- for testing purposes, not a real thing
  6178. );
  6179. )sql");
  6180. UNIT_ASSERT_C(res.Root, res.Issues.ToString());
  6181. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  6182. if (word == "Write") {
  6183. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(R"#('"TestCollection")#"));
  6184. UNIT_ASSERT_STRING_CONTAINS(line, R"#(('"storage" (String '"local")))#");
  6185. UNIT_ASSERT_STRING_CONTAINS(line, R"#(('"tag" (String '"test"))))#");
  6186. UNIT_ASSERT_STRING_CONTAINS(line, R"#(('entries '()))#");
  6187. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("'create"));
  6188. }
  6189. };
  6190. TWordCountHive elementStat = { {TString("Write"), 0} };
  6191. VerifyProgram(res, elementStat, verifyLine);
  6192. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  6193. }
  6194. Y_UNIT_TEST(CreateBackupCollectionWithDatabase) {
  6195. NYql::TAstParseResult res = SqlToYql(R"sql(
  6196. USE plato;
  6197. CREATE BACKUP COLLECTION TestCollection DATABASE WITH (
  6198. STORAGE="local",
  6199. TAG="test" -- for testing purposes, not a real thing
  6200. );
  6201. )sql");
  6202. UNIT_ASSERT_C(res.Root, res.Issues.ToString());
  6203. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  6204. if (word == "Write") {
  6205. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(R"#('"TestCollection")#"));
  6206. UNIT_ASSERT_STRING_CONTAINS(line, R"#(('"storage" (String '"local")))#");
  6207. UNIT_ASSERT_STRING_CONTAINS(line, R"#(('"tag" (String '"test"))))#");
  6208. UNIT_ASSERT_STRING_CONTAINS(line, R"#(('entries '('('('type 'database)))))#");
  6209. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("'create"));
  6210. }
  6211. };
  6212. TWordCountHive elementStat = { {TString("Write"), 0} };
  6213. VerifyProgram(res, elementStat, verifyLine);
  6214. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  6215. }
  6216. Y_UNIT_TEST(CreateBackupCollectionWithTables) {
  6217. NYql::TAstParseResult res = SqlToYql(R"sql(
  6218. USE plato;
  6219. CREATE BACKUP COLLECTION TestCollection (
  6220. TABLE someTable,
  6221. TABLE `prefix/anotherTable`
  6222. ) WITH (
  6223. STORAGE="local",
  6224. TAG="test" -- for testing purposes, not a real thing
  6225. );
  6226. )sql");
  6227. UNIT_ASSERT_C(res.Root, res.Issues.ToString());
  6228. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  6229. if (word == "Write") {
  6230. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(R"#('"TestCollection")#"));
  6231. UNIT_ASSERT_STRING_CONTAINS(line, R"#(('"storage" (String '"local")))#");
  6232. UNIT_ASSERT_STRING_CONTAINS(line, R"#(('"tag" (String '"test"))))#");
  6233. UNIT_ASSERT_STRING_CONTAINS(line, R"#(('entries '('('('type 'table) '('path '"someTable")) '('('type 'table) '('path '"prefix/anotherTable")))))#");
  6234. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("'create"));
  6235. }
  6236. };
  6237. TWordCountHive elementStat = { {TString("Write"), 0} };
  6238. VerifyProgram(res, elementStat, verifyLine);
  6239. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  6240. }
  6241. Y_UNIT_TEST(CreateBackupCollectionWithBadArguments) {
  6242. ExpectFailWithError(R"sql(
  6243. USE plato;
  6244. CREATE BACKUP COLLECTION TestCollection;
  6245. )sql" , "<main>:3:55: Error: mismatched input ';' expecting {'(', DATABASE, WITH}\n");
  6246. ExpectFailWithError(R"sql(
  6247. USE plato;
  6248. CREATE BACKUP COLLECTION TABLE TestCollection;
  6249. )sql" , "<main>:3:47: Error: mismatched input 'TestCollection' expecting {'(', DATABASE, WITH}\n");
  6250. ExpectFailWithError(R"sql(
  6251. USE plato;
  6252. CREATE BACKUP COLLECTION DATABASE `test` TestCollection;
  6253. )sql" , "<main>:3:50: Error: mismatched input '`test`' expecting {'(', DATABASE, WITH}\n");
  6254. ExpectFailWithError(R"sql(
  6255. USE plato;
  6256. CREATE BACKUP COLLECTION TestCollection WITH (
  6257. DUPLICATE_SETTING="first_value",
  6258. DUPLICATE_SETTING="second_value"
  6259. );
  6260. )sql" , "<main>:5:21: Error: DUPLICATE_SETTING duplicate keys\n");
  6261. ExpectFailWithError(R"sql(
  6262. USE plato;
  6263. CREATE BACKUP COLLECTION TestCollection WITH (
  6264. INT_SETTING=1
  6265. );
  6266. )sql" , "<main>:4:21: Error: INT_SETTING value should be a string literal\n");
  6267. }
  6268. Y_UNIT_TEST(AlterBackupCollection) {
  6269. NYql::TAstParseResult res = SqlToYql(R"sql(
  6270. USE plato;
  6271. ALTER BACKUP COLLECTION TestCollection
  6272. SET (STORAGE="remote"), -- also just for test
  6273. SET (TAG1 = "123"),
  6274. RESET (TAG2, TAG3);
  6275. )sql");
  6276. UNIT_ASSERT_C(res.Root, res.Issues.ToString());
  6277. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  6278. if (word == "Write") {
  6279. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(R"#('"TestCollection")#"));
  6280. UNIT_ASSERT_STRING_CONTAINS(line, R"#(('mode 'alter))#");
  6281. UNIT_ASSERT_STRING_CONTAINS(line, R"#(('"storage" (String '"remote")))#");
  6282. UNIT_ASSERT_STRING_CONTAINS(line, R"#(('"tag1" (String '"123"))))#");
  6283. UNIT_ASSERT_STRING_CONTAINS(line, R"#('('resetSettings '('"tag2" '"tag3")))#");
  6284. }
  6285. };
  6286. TWordCountHive elementStat = { {TString("Write"), 0} };
  6287. VerifyProgram(res, elementStat, verifyLine);
  6288. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  6289. }
  6290. Y_UNIT_TEST(AlterBackupCollectionEntries) {
  6291. NYql::TAstParseResult res = SqlToYql(R"sql(
  6292. USE plato;
  6293. ALTER BACKUP COLLECTION TestCollection
  6294. DROP TABLE `test`,
  6295. ADD DATABASE;
  6296. )sql");
  6297. UNIT_ASSERT_C(res.Root, res.Issues.ToString());
  6298. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  6299. if (word == "Write") {
  6300. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(R"#('"TestCollection")#"));
  6301. UNIT_ASSERT_STRING_CONTAINS(line, R"#(('mode 'alter))#");
  6302. UNIT_ASSERT_STRING_CONTAINS(line, R"#('alterEntries)#");
  6303. UNIT_ASSERT_STRING_CONTAINS(line, R"#('('('type 'table) '('path '"test") '('action 'drop)))#");
  6304. UNIT_ASSERT_STRING_CONTAINS(line, R"#('('('type 'database) '('action 'add)))#");
  6305. }
  6306. };
  6307. TWordCountHive elementStat = { {TString("Write"), 0} };
  6308. VerifyProgram(res, elementStat, verifyLine);
  6309. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  6310. }
  6311. Y_UNIT_TEST(DropBackupCollection) {
  6312. NYql::TAstParseResult res = SqlToYql(R"sql(
  6313. USE plato;
  6314. DROP BACKUP COLLECTION TestCollection;
  6315. )sql");
  6316. UNIT_ASSERT(res.Root);
  6317. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  6318. if (word == "Write") {
  6319. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(R"#('"TestCollection")#"));
  6320. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("drop"));
  6321. }
  6322. };
  6323. TWordCountHive elementStat = { {TString("Write"), 0}};
  6324. VerifyProgram(res, elementStat, verifyLine);
  6325. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  6326. }
  6327. }
  6328. Y_UNIT_TEST_SUITE(ResourcePoolClassifier) {
  6329. Y_UNIT_TEST(CreateResourcePoolClassifier) {
  6330. NYql::TAstParseResult res = SqlToYql(R"sql(
  6331. USE plato;
  6332. CREATE RESOURCE POOL CLASSIFIER MyResourcePoolClassifier WITH (
  6333. RANK=20,
  6334. RESOURCE_POOL='wgUserQueries',
  6335. MEMBER_NAME='yandex_query@abc'
  6336. );
  6337. )sql");
  6338. UNIT_ASSERT_C(res.Root, res.Issues.ToString());
  6339. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  6340. if (word == "Write") {
  6341. UNIT_ASSERT_STRING_CONTAINS(line, R"#('('('"member_name" '"yandex_query@abc") '('"rank" (Int32 '"20")) '('"resource_pool" '"wgUserQueries"))#");
  6342. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("createObject"));
  6343. }
  6344. };
  6345. TWordCountHive elementStat = { {TString("Write"), 0} };
  6346. VerifyProgram(res, elementStat, verifyLine);
  6347. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  6348. }
  6349. Y_UNIT_TEST(CreateResourcePoolClassifierWithBadArguments) {
  6350. ExpectFailWithError(R"sql(
  6351. USE plato;
  6352. CREATE RESOURCE POOL CLASSIFIER MyResourcePoolClassifier;
  6353. )sql" , "<main>:3:72: Error: mismatched input ';' expecting WITH\n");
  6354. ExpectFailWithError(R"sql(
  6355. USE plato;
  6356. CREATE RESOURCE POOL CLASSIFIER MyResourcePoolClassifier WITH (
  6357. DUPLICATE_SETTING="first_value",
  6358. DUPLICATE_SETTING="second_value"
  6359. );
  6360. )sql" , "<main>:5:21: Error: DUPLICATE_SETTING duplicate keys\n");
  6361. }
  6362. Y_UNIT_TEST(AlterResourcePoolClassifier) {
  6363. NYql::TAstParseResult res = SqlToYql(R"sql(
  6364. USE plato;
  6365. ALTER RESOURCE POOL CLASSIFIER MyResourcePoolClassifier
  6366. SET (RANK = 30, Weight = 5, MEMBER_NAME = "test@user"),
  6367. RESET (Resource_Pool);
  6368. )sql");
  6369. UNIT_ASSERT_C(res.Root, res.Issues.ToString());
  6370. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  6371. if (word == "Write") {
  6372. UNIT_ASSERT_STRING_CONTAINS(line, R"#(('mode 'alterObject))#");
  6373. UNIT_ASSERT_STRING_CONTAINS(line, R"#('('features '('('"member_name" '"test@user") '('"rank" (Int32 '"30")) '('"weight" (Int32 '"5")))))#");
  6374. UNIT_ASSERT_STRING_CONTAINS(line, R"#('('resetFeatures '('"resource_pool")))#");
  6375. }
  6376. };
  6377. TWordCountHive elementStat = { {TString("Write"), 0} };
  6378. VerifyProgram(res, elementStat, verifyLine);
  6379. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  6380. }
  6381. Y_UNIT_TEST(DropResourcePoolClassifier) {
  6382. NYql::TAstParseResult res = SqlToYql(R"sql(
  6383. USE plato;
  6384. DROP RESOURCE POOL CLASSIFIER MyResourcePoolClassifier;
  6385. )sql");
  6386. UNIT_ASSERT(res.Root);
  6387. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  6388. if (word == "Write") {
  6389. UNIT_ASSERT_VALUES_EQUAL(TString::npos, line.find("'features"));
  6390. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("dropObject"));
  6391. }
  6392. };
  6393. TWordCountHive elementStat = { {TString("Write"), 0}};
  6394. VerifyProgram(res, elementStat, verifyLine);
  6395. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  6396. }
  6397. Y_UNIT_TEST(BacktickMatching) {
  6398. auto req = "select\n"
  6399. " 1 as `Schema has \\`RealCost\\``\n"
  6400. " -- foo`bar";
  6401. auto res = SqlToYql(req);
  6402. UNIT_ASSERT(res.Root);
  6403. UNIT_ASSERT(res.IsOk());
  6404. UNIT_ASSERT(res.Issues.Size() == 0);
  6405. res = SqlToYqlWithAnsiLexer(req);
  6406. UNIT_ASSERT(res.Root);
  6407. UNIT_ASSERT(res.IsOk());
  6408. UNIT_ASSERT(res.Issues.Size() == 0);
  6409. req = "select 1 as `a``b`, 2 as ````, 3 as `\\x60a\\x60`, 4 as ```b```, 5 as `\\`c\\``";
  6410. res = SqlToYql(req);
  6411. UNIT_ASSERT(res.Root);
  6412. UNIT_ASSERT(res.IsOk());
  6413. UNIT_ASSERT(res.Issues.Size() == 0);
  6414. res = SqlToYqlWithAnsiLexer(req);
  6415. UNIT_ASSERT(res.Root);
  6416. UNIT_ASSERT(res.IsOk());
  6417. UNIT_ASSERT(res.Issues.Size() == 0);
  6418. }
  6419. }
  6420. Y_UNIT_TEST_SUITE(Backup) {
  6421. Y_UNIT_TEST(Simple) {
  6422. NYql::TAstParseResult res = SqlToYql(R"sql(
  6423. USE plato;
  6424. BACKUP TestCollection;
  6425. )sql");
  6426. UNIT_ASSERT_C(res.Root, res.Issues.ToString());
  6427. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  6428. if (word == "Write") {
  6429. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(R"#('"TestCollection")#"));
  6430. UNIT_ASSERT_VALUES_EQUAL(TString::npos, line.find("'Incremental"));
  6431. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("'backup"));
  6432. }
  6433. };
  6434. TWordCountHive elementStat = { {TString("Write"), 0} };
  6435. VerifyProgram(res, elementStat, verifyLine);
  6436. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  6437. }
  6438. Y_UNIT_TEST(Incremental) {
  6439. NYql::TAstParseResult res = SqlToYql(R"sql(
  6440. USE plato;
  6441. BACKUP TestCollection INCREMENTAL;
  6442. )sql");
  6443. UNIT_ASSERT_C(res.Root, res.Issues.ToString());
  6444. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  6445. if (word == "Write") {
  6446. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(R"#('"TestCollection")#"));
  6447. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("'backupIncremental"));
  6448. }
  6449. };
  6450. TWordCountHive elementStat = { {TString("Write"), 0} };
  6451. VerifyProgram(res, elementStat, verifyLine);
  6452. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  6453. }
  6454. }
  6455. Y_UNIT_TEST_SUITE(Restore) {
  6456. Y_UNIT_TEST(Simple) {
  6457. NYql::TAstParseResult res = SqlToYql(R"sql(
  6458. USE plato;
  6459. RESTORE TestCollection;
  6460. )sql");
  6461. UNIT_ASSERT_C(res.Root, res.Issues.ToString());
  6462. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  6463. if (word == "Write") {
  6464. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(R"#('"TestCollection")#"));
  6465. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("'restore"));
  6466. }
  6467. };
  6468. TWordCountHive elementStat = { {TString("Write"), 0} };
  6469. VerifyProgram(res, elementStat, verifyLine);
  6470. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  6471. }
  6472. Y_UNIT_TEST(AtPoint) {
  6473. NYql::TAstParseResult res = SqlToYql(R"sql(
  6474. USE plato;
  6475. RESTORE TestCollection AT '2024-06-16_20-14-02';
  6476. )sql");
  6477. UNIT_ASSERT_C(res.Root, res.Issues.ToString());
  6478. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  6479. if (word == "Write") {
  6480. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find(R"#('"TestCollection")#"));
  6481. UNIT_ASSERT_STRING_CONTAINS(line, R"#('at '"2024-06-16_20-14-02")#");
  6482. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("'restore"));
  6483. }
  6484. };
  6485. TWordCountHive elementStat = { {TString("Write"), 0} };
  6486. VerifyProgram(res, elementStat, verifyLine);
  6487. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  6488. }
  6489. }
  6490. Y_UNIT_TEST_SUITE(ColumnFamily) {
  6491. Y_UNIT_TEST(CompressionLevelCorrectUsage) {
  6492. NYql::TAstParseResult res = SqlToYql(R"( use plato;
  6493. CREATE TABLE tableName (
  6494. Key Uint32 FAMILY default,
  6495. Value String FAMILY family1,
  6496. PRIMARY KEY (Key),
  6497. FAMILY default (
  6498. DATA = "test",
  6499. COMPRESSION = "lz4",
  6500. COMPRESSION_LEVEL = 5
  6501. ),
  6502. FAMILY family1 (
  6503. DATA = "test",
  6504. COMPRESSION = "lz4",
  6505. COMPRESSION_LEVEL = 3
  6506. )
  6507. );
  6508. )");
  6509. UNIT_ASSERT(res.IsOk());
  6510. UNIT_ASSERT(res.Issues.Size() == 0);
  6511. TVerifyLineFunc verifyLine = [](const TString& word, const TString& line) {
  6512. if (word == "Write") {
  6513. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("compression_level"));
  6514. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("5"));
  6515. UNIT_ASSERT_VALUES_UNEQUAL(TString::npos, line.find("3"));
  6516. }
  6517. };
  6518. TWordCountHive elementStat = { { TString("Write"), 0 }, { TString("compression_level"), 0 } };
  6519. VerifyProgram(res, elementStat, verifyLine);
  6520. UNIT_ASSERT_VALUES_EQUAL(1, elementStat["Write"]);
  6521. UNIT_ASSERT_VALUES_EQUAL(2, elementStat["compression_level"]);
  6522. }
  6523. Y_UNIT_TEST(FieldDataIsNotString) {
  6524. NYql::TAstParseResult res = SqlToYql(R"( use plato;
  6525. CREATE TABLE tableName (
  6526. Key Uint32 FAMILY default,
  6527. PRIMARY KEY (Key),
  6528. FAMILY default (
  6529. DATA = 1,
  6530. COMPRESSION = "lz4",
  6531. COMPRESSION_LEVEL = 5
  6532. )
  6533. );
  6534. )");
  6535. UNIT_ASSERT(!res.IsOk());
  6536. UNIT_ASSERT(res.Issues.Size() == 1);
  6537. UNIT_ASSERT_STRING_CONTAINS(res.Issues.ToString(), "DATA value should be a string literal");
  6538. }
  6539. Y_UNIT_TEST(FieldCompressionIsNotString) {
  6540. NYql::TAstParseResult res = SqlToYql(R"( use plato;
  6541. CREATE TABLE tableName (
  6542. Key Uint32 FAMILY default,
  6543. PRIMARY KEY (Key),
  6544. FAMILY default (
  6545. DATA = "test",
  6546. COMPRESSION = 2,
  6547. COMPRESSION_LEVEL = 5
  6548. ),
  6549. );
  6550. )");
  6551. UNIT_ASSERT(!res.IsOk());
  6552. UNIT_ASSERT(res.Issues.Size() == 1);
  6553. UNIT_ASSERT_STRING_CONTAINS(res.Issues.ToString(), "COMPRESSION value should be a string literal");
  6554. }
  6555. Y_UNIT_TEST(FieldCompressionLevelIsNotInteger) {
  6556. NYql::TAstParseResult res = SqlToYql(R"( use plato;
  6557. CREATE TABLE tableName (
  6558. Key Uint32 FAMILY default,
  6559. PRIMARY KEY (Key),
  6560. FAMILY default (
  6561. DATA = "test",
  6562. COMPRESSION = "lz4",
  6563. COMPRESSION_LEVEL = "5"
  6564. )
  6565. );
  6566. )");
  6567. UNIT_ASSERT(!res.IsOk());
  6568. UNIT_ASSERT(res.Issues.Size() == 1);
  6569. UNIT_ASSERT_STRING_CONTAINS(res.Issues.ToString(), "COMPRESSION_LEVEL value should be an integer");
  6570. }
  6571. Y_UNIT_TEST(AlterCompressionCorrectUsage) {
  6572. NYql::TAstParseResult res = SqlToYql(R"( use plato;
  6573. ALTER TABLE tableName ALTER FAMILY default SET COMPRESSION "lz4";
  6574. )");
  6575. UNIT_ASSERT(res.IsOk());
  6576. UNIT_ASSERT(res.Issues.Size() == 0);
  6577. }
  6578. Y_UNIT_TEST(AlterCompressionFieldIsNotString) {
  6579. NYql::TAstParseResult res = SqlToYql(R"( use plato;
  6580. ALTER TABLE tableName ALTER FAMILY default SET COMPRESSION lz4;
  6581. )");
  6582. UNIT_ASSERT(!res.IsOk());
  6583. UNIT_ASSERT(res.Issues.Size() == 1);
  6584. UNIT_ASSERT_STRING_CONTAINS(res.Issues.ToString(), "mismatched input 'lz4' expecting {STRING_VALUE, DIGITS, INTEGER_VALUE}");
  6585. }
  6586. Y_UNIT_TEST(AlterCompressionLevelCorrectUsage) {
  6587. NYql::TAstParseResult res = SqlToYql(R"( use plato;
  6588. ALTER TABLE tableName ALTER FAMILY default SET COMPRESSION_LEVEL 5;
  6589. )");
  6590. UNIT_ASSERT(res.IsOk());
  6591. UNIT_ASSERT(res.Issues.Size() == 0);
  6592. }
  6593. Y_UNIT_TEST(AlterCompressionLevelFieldIsNotInteger) {
  6594. NYql::TAstParseResult res = SqlToYql(R"( use plato;
  6595. ALTER TABLE tableName ALTER FAMILY default SET COMPRESSION_LEVEL "5";
  6596. )");
  6597. UNIT_ASSERT(!res.IsOk());
  6598. UNIT_ASSERT(res.Issues.Size() == 1);
  6599. UNIT_ASSERT_STRING_CONTAINS(res.Issues.ToString(), "COMPRESSION_LEVEL value should be an integer");
  6600. }
  6601. }