sql_ut_antlr4.cpp 348 KB

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