sql_ut.cpp 348 KB

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