ast.go 156 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814
  1. package influxql
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "math"
  7. "regexp"
  8. "regexp/syntax"
  9. "sort"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "github.com/gogo/protobuf/proto"
  14. internal "github.com/influxdata/influxql/internal"
  15. )
  16. // DataType represents the primitive data types available in InfluxQL.
  17. type DataType int
  18. const (
  19. // Unknown primitive data type.
  20. Unknown DataType = 0
  21. // Float means the data type is a float.
  22. Float DataType = 1
  23. // Integer means the data type is an integer.
  24. Integer DataType = 2
  25. // String means the data type is a string of text.
  26. String DataType = 3
  27. // Boolean means the data type is a boolean.
  28. Boolean DataType = 4
  29. // Time means the data type is a time.
  30. Time DataType = 5
  31. // Duration means the data type is a duration of time.
  32. Duration DataType = 6
  33. // Tag means the data type is a tag.
  34. Tag DataType = 7
  35. // AnyField means the data type is any field.
  36. AnyField DataType = 8
  37. // Unsigned means the data type is an unsigned integer.
  38. Unsigned DataType = 9
  39. )
  40. const (
  41. // MinTime is the minumum time that can be represented.
  42. //
  43. // 1677-09-21 00:12:43.145224194 +0000 UTC
  44. //
  45. // The two lowest minimum integers are used as sentinel values. The
  46. // minimum value needs to be used as a value lower than any other value for
  47. // comparisons and another separate value is needed to act as a sentinel
  48. // default value that is unusable by the user, but usable internally.
  49. // Because these two values need to be used for a special purpose, we do
  50. // not allow users to write points at these two times.
  51. MinTime = int64(math.MinInt64) + 2
  52. // MaxTime is the maximum time that can be represented.
  53. //
  54. // 2262-04-11 23:47:16.854775806 +0000 UTC
  55. //
  56. // The highest time represented by a nanosecond needs to be used for an
  57. // exclusive range in the shard group, so the maximum time needs to be one
  58. // less than the possible maximum number of nanoseconds representable by an
  59. // int64 so that we don't lose a point at that one time.
  60. MaxTime = int64(math.MaxInt64) - 1
  61. )
  62. var (
  63. // ErrInvalidTime is returned when the timestamp string used to
  64. // compare against time field is invalid.
  65. ErrInvalidTime = errors.New("invalid timestamp string")
  66. )
  67. // InspectDataType returns the data type of a given value.
  68. func InspectDataType(v interface{}) DataType {
  69. switch v.(type) {
  70. case float64:
  71. return Float
  72. case int64, int32, int:
  73. return Integer
  74. case string:
  75. return String
  76. case bool:
  77. return Boolean
  78. case uint64:
  79. return Unsigned
  80. case time.Time:
  81. return Time
  82. case time.Duration:
  83. return Duration
  84. default:
  85. return Unknown
  86. }
  87. }
  88. // DataTypeFromString returns a data type given the string representation of that
  89. // data type.
  90. func DataTypeFromString(s string) DataType {
  91. switch s {
  92. case "float":
  93. return Float
  94. case "integer":
  95. return Integer
  96. case "unsigned":
  97. return Unsigned
  98. case "string":
  99. return String
  100. case "boolean":
  101. return Boolean
  102. case "time":
  103. return Time
  104. case "duration":
  105. return Duration
  106. case "tag":
  107. return Tag
  108. case "field":
  109. return AnyField
  110. default:
  111. return Unknown
  112. }
  113. }
  114. // LessThan returns true if the other DataType has greater precedence than the
  115. // current data type. Unknown has the lowest precedence.
  116. //
  117. // NOTE: This is not the same as using the `<` or `>` operator because the
  118. // integers used decrease with higher precedence, but Unknown is the lowest
  119. // precedence at the zero value.
  120. func (d DataType) LessThan(other DataType) bool {
  121. if d == Unknown {
  122. return true
  123. } else if d == Unsigned {
  124. return other != Unknown && other <= Integer
  125. } else if other == Unsigned {
  126. return d >= String
  127. }
  128. return other != Unknown && other < d
  129. }
  130. var (
  131. zeroFloat64 interface{} = float64(0)
  132. zeroInt64 interface{} = int64(0)
  133. zeroUint64 interface{} = uint64(0)
  134. zeroString interface{} = ""
  135. zeroBoolean interface{} = false
  136. zeroTime interface{} = time.Time{}
  137. zeroDuration interface{} = time.Duration(0)
  138. )
  139. // Zero returns the zero value for the DataType.
  140. // The return value of this method, when sent back to InspectDataType,
  141. // may not produce the same value.
  142. func (d DataType) Zero() interface{} {
  143. switch d {
  144. case Float:
  145. return zeroFloat64
  146. case Integer:
  147. return zeroInt64
  148. case Unsigned:
  149. return zeroUint64
  150. case String, Tag:
  151. return zeroString
  152. case Boolean:
  153. return zeroBoolean
  154. case Time:
  155. return zeroTime
  156. case Duration:
  157. return zeroDuration
  158. }
  159. return nil
  160. }
  161. // String returns the human-readable string representation of the DataType.
  162. func (d DataType) String() string {
  163. switch d {
  164. case Float:
  165. return "float"
  166. case Integer:
  167. return "integer"
  168. case Unsigned:
  169. return "unsigned"
  170. case String:
  171. return "string"
  172. case Boolean:
  173. return "boolean"
  174. case Time:
  175. return "time"
  176. case Duration:
  177. return "duration"
  178. case Tag:
  179. return "tag"
  180. case AnyField:
  181. return "field"
  182. }
  183. return "unknown"
  184. }
  185. // Node represents a node in the InfluxDB abstract syntax tree.
  186. type Node interface {
  187. // node is unexported to ensure implementations of Node
  188. // can only originate in this package.
  189. node()
  190. String() string
  191. }
  192. func (*Query) node() {}
  193. func (Statements) node() {}
  194. func (*AlterRetentionPolicyStatement) node() {}
  195. func (*CreateContinuousQueryStatement) node() {}
  196. func (*CreateDatabaseStatement) node() {}
  197. func (*CreateRetentionPolicyStatement) node() {}
  198. func (*CreateSubscriptionStatement) node() {}
  199. func (*CreateUserStatement) node() {}
  200. func (*Distinct) node() {}
  201. func (*DeleteSeriesStatement) node() {}
  202. func (*DeleteStatement) node() {}
  203. func (*DropContinuousQueryStatement) node() {}
  204. func (*DropDatabaseStatement) node() {}
  205. func (*DropMeasurementStatement) node() {}
  206. func (*DropRetentionPolicyStatement) node() {}
  207. func (*DropSeriesStatement) node() {}
  208. func (*DropShardStatement) node() {}
  209. func (*DropSubscriptionStatement) node() {}
  210. func (*DropUserStatement) node() {}
  211. func (*ExplainStatement) node() {}
  212. func (*GrantStatement) node() {}
  213. func (*GrantAdminStatement) node() {}
  214. func (*KillQueryStatement) node() {}
  215. func (*RevokeStatement) node() {}
  216. func (*RevokeAdminStatement) node() {}
  217. func (*SelectStatement) node() {}
  218. func (*SetPasswordUserStatement) node() {}
  219. func (*ShowContinuousQueriesStatement) node() {}
  220. func (*ShowGrantsForUserStatement) node() {}
  221. func (*ShowDatabasesStatement) node() {}
  222. func (*ShowFieldKeyCardinalityStatement) node() {}
  223. func (*ShowFieldKeysStatement) node() {}
  224. func (*ShowRetentionPoliciesStatement) node() {}
  225. func (*ShowMeasurementCardinalityStatement) node() {}
  226. func (*ShowMeasurementsStatement) node() {}
  227. func (*ShowQueriesStatement) node() {}
  228. func (*ShowSeriesStatement) node() {}
  229. func (*ShowSeriesCardinalityStatement) node() {}
  230. func (*ShowShardGroupsStatement) node() {}
  231. func (*ShowShardsStatement) node() {}
  232. func (*ShowStatsStatement) node() {}
  233. func (*ShowSubscriptionsStatement) node() {}
  234. func (*ShowDiagnosticsStatement) node() {}
  235. func (*ShowTagKeyCardinalityStatement) node() {}
  236. func (*ShowTagKeysStatement) node() {}
  237. func (*ShowTagValuesCardinalityStatement) node() {}
  238. func (*ShowTagValuesStatement) node() {}
  239. func (*ShowUsersStatement) node() {}
  240. func (*BinaryExpr) node() {}
  241. func (*BooleanLiteral) node() {}
  242. func (*BoundParameter) node() {}
  243. func (*Call) node() {}
  244. func (*Dimension) node() {}
  245. func (Dimensions) node() {}
  246. func (*DurationLiteral) node() {}
  247. func (*IntegerLiteral) node() {}
  248. func (*UnsignedLiteral) node() {}
  249. func (*Field) node() {}
  250. func (Fields) node() {}
  251. func (*Measurement) node() {}
  252. func (Measurements) node() {}
  253. func (*NilLiteral) node() {}
  254. func (*NumberLiteral) node() {}
  255. func (*ParenExpr) node() {}
  256. func (*RegexLiteral) node() {}
  257. func (*ListLiteral) node() {}
  258. func (*SortField) node() {}
  259. func (SortFields) node() {}
  260. func (Sources) node() {}
  261. func (*StringLiteral) node() {}
  262. func (*SubQuery) node() {}
  263. func (*Target) node() {}
  264. func (*TimeLiteral) node() {}
  265. func (*VarRef) node() {}
  266. func (*Wildcard) node() {}
  267. // Query represents a collection of ordered statements.
  268. type Query struct {
  269. Statements Statements
  270. }
  271. // String returns a string representation of the query.
  272. func (q *Query) String() string { return q.Statements.String() }
  273. // Statements represents a list of statements.
  274. type Statements []Statement
  275. // String returns a string representation of the statements.
  276. func (a Statements) String() string {
  277. var str []string
  278. for _, stmt := range a {
  279. str = append(str, stmt.String())
  280. }
  281. return strings.Join(str, ";\n")
  282. }
  283. // Statement represents a single command in InfluxQL.
  284. type Statement interface {
  285. Node
  286. // stmt is unexported to ensure implementations of Statement
  287. // can only originate in this package.
  288. stmt()
  289. RequiredPrivileges() (ExecutionPrivileges, error)
  290. }
  291. // HasDefaultDatabase provides an interface to get the default database from a Statement.
  292. type HasDefaultDatabase interface {
  293. Node
  294. // stmt is unexported to ensure implementations of HasDefaultDatabase
  295. // can only originate in this package.
  296. stmt()
  297. DefaultDatabase() string
  298. }
  299. // ExecutionPrivilege is a privilege required for a user to execute
  300. // a statement on a database or resource.
  301. type ExecutionPrivilege struct {
  302. // Admin privilege required.
  303. Admin bool
  304. // Name of the database.
  305. Name string
  306. // Database privilege required.
  307. Privilege Privilege
  308. }
  309. // ExecutionPrivileges is a list of privileges required to execute a statement.
  310. type ExecutionPrivileges []ExecutionPrivilege
  311. func (*AlterRetentionPolicyStatement) stmt() {}
  312. func (*CreateContinuousQueryStatement) stmt() {}
  313. func (*CreateDatabaseStatement) stmt() {}
  314. func (*CreateRetentionPolicyStatement) stmt() {}
  315. func (*CreateSubscriptionStatement) stmt() {}
  316. func (*CreateUserStatement) stmt() {}
  317. func (*DeleteSeriesStatement) stmt() {}
  318. func (*DeleteStatement) stmt() {}
  319. func (*DropContinuousQueryStatement) stmt() {}
  320. func (*DropDatabaseStatement) stmt() {}
  321. func (*DropMeasurementStatement) stmt() {}
  322. func (*DropRetentionPolicyStatement) stmt() {}
  323. func (*DropSeriesStatement) stmt() {}
  324. func (*DropSubscriptionStatement) stmt() {}
  325. func (*DropUserStatement) stmt() {}
  326. func (*ExplainStatement) stmt() {}
  327. func (*GrantStatement) stmt() {}
  328. func (*GrantAdminStatement) stmt() {}
  329. func (*KillQueryStatement) stmt() {}
  330. func (*ShowContinuousQueriesStatement) stmt() {}
  331. func (*ShowGrantsForUserStatement) stmt() {}
  332. func (*ShowDatabasesStatement) stmt() {}
  333. func (*ShowFieldKeyCardinalityStatement) stmt() {}
  334. func (*ShowFieldKeysStatement) stmt() {}
  335. func (*ShowMeasurementCardinalityStatement) stmt() {}
  336. func (*ShowMeasurementsStatement) stmt() {}
  337. func (*ShowQueriesStatement) stmt() {}
  338. func (*ShowRetentionPoliciesStatement) stmt() {}
  339. func (*ShowSeriesStatement) stmt() {}
  340. func (*ShowSeriesCardinalityStatement) stmt() {}
  341. func (*ShowShardGroupsStatement) stmt() {}
  342. func (*ShowShardsStatement) stmt() {}
  343. func (*ShowStatsStatement) stmt() {}
  344. func (*DropShardStatement) stmt() {}
  345. func (*ShowSubscriptionsStatement) stmt() {}
  346. func (*ShowDiagnosticsStatement) stmt() {}
  347. func (*ShowTagKeyCardinalityStatement) stmt() {}
  348. func (*ShowTagKeysStatement) stmt() {}
  349. func (*ShowTagValuesCardinalityStatement) stmt() {}
  350. func (*ShowTagValuesStatement) stmt() {}
  351. func (*ShowUsersStatement) stmt() {}
  352. func (*RevokeStatement) stmt() {}
  353. func (*RevokeAdminStatement) stmt() {}
  354. func (*SelectStatement) stmt() {}
  355. func (*SetPasswordUserStatement) stmt() {}
  356. // Expr represents an expression that can be evaluated to a value.
  357. type Expr interface {
  358. Node
  359. // expr is unexported to ensure implementations of Expr
  360. // can only originate in this package.
  361. expr()
  362. }
  363. func (*BinaryExpr) expr() {}
  364. func (*BooleanLiteral) expr() {}
  365. func (*BoundParameter) expr() {}
  366. func (*Call) expr() {}
  367. func (*Distinct) expr() {}
  368. func (*DurationLiteral) expr() {}
  369. func (*IntegerLiteral) expr() {}
  370. func (*UnsignedLiteral) expr() {}
  371. func (*NilLiteral) expr() {}
  372. func (*NumberLiteral) expr() {}
  373. func (*ParenExpr) expr() {}
  374. func (*RegexLiteral) expr() {}
  375. func (*ListLiteral) expr() {}
  376. func (*StringLiteral) expr() {}
  377. func (*TimeLiteral) expr() {}
  378. func (*VarRef) expr() {}
  379. func (*Wildcard) expr() {}
  380. // Literal represents a static literal.
  381. type Literal interface {
  382. Expr
  383. // literal is unexported to ensure implementations of Literal
  384. // can only originate in this package.
  385. literal()
  386. }
  387. func (*BooleanLiteral) literal() {}
  388. func (*BoundParameter) literal() {}
  389. func (*DurationLiteral) literal() {}
  390. func (*IntegerLiteral) literal() {}
  391. func (*UnsignedLiteral) literal() {}
  392. func (*NilLiteral) literal() {}
  393. func (*NumberLiteral) literal() {}
  394. func (*RegexLiteral) literal() {}
  395. func (*ListLiteral) literal() {}
  396. func (*StringLiteral) literal() {}
  397. func (*TimeLiteral) literal() {}
  398. // Source represents a source of data for a statement.
  399. type Source interface {
  400. Node
  401. // source is unexported to ensure implementations of Source
  402. // can only originate in this package.
  403. source()
  404. }
  405. func (*Measurement) source() {}
  406. func (*SubQuery) source() {}
  407. // Sources represents a list of sources.
  408. type Sources []Source
  409. // String returns a string representation of a Sources array.
  410. func (a Sources) String() string {
  411. var buf bytes.Buffer
  412. ubound := len(a) - 1
  413. for i, src := range a {
  414. _, _ = buf.WriteString(src.String())
  415. if i < ubound {
  416. _, _ = buf.WriteString(", ")
  417. }
  418. }
  419. return buf.String()
  420. }
  421. // Measurements returns all measurements including ones embedded in subqueries.
  422. func (a Sources) Measurements() []*Measurement {
  423. mms := make([]*Measurement, 0, len(a))
  424. for _, src := range a {
  425. switch src := src.(type) {
  426. case *Measurement:
  427. mms = append(mms, src)
  428. case *SubQuery:
  429. mms = append(mms, src.Statement.Sources.Measurements()...)
  430. }
  431. }
  432. return mms
  433. }
  434. // MarshalBinary encodes a list of sources to a binary format.
  435. func (a Sources) MarshalBinary() ([]byte, error) {
  436. var pb internal.Measurements
  437. pb.Items = make([]*internal.Measurement, len(a))
  438. for i, source := range a {
  439. pb.Items[i] = encodeMeasurement(source.(*Measurement))
  440. }
  441. return proto.Marshal(&pb)
  442. }
  443. // UnmarshalBinary decodes binary data into a list of sources.
  444. func (a *Sources) UnmarshalBinary(buf []byte) error {
  445. var pb internal.Measurements
  446. if err := proto.Unmarshal(buf, &pb); err != nil {
  447. return err
  448. }
  449. *a = make(Sources, len(pb.GetItems()))
  450. for i := range pb.GetItems() {
  451. mm, err := decodeMeasurement(pb.GetItems()[i])
  452. if err != nil {
  453. return err
  454. }
  455. (*a)[i] = mm
  456. }
  457. return nil
  458. }
  459. // RequiredPrivileges recursively returns a list of execution privileges required.
  460. func (a Sources) RequiredPrivileges() (ExecutionPrivileges, error) {
  461. var ep ExecutionPrivileges
  462. for _, source := range a {
  463. switch source := source.(type) {
  464. case *Measurement:
  465. ep = append(ep, ExecutionPrivilege{
  466. Name: source.Database,
  467. Privilege: ReadPrivilege,
  468. })
  469. case *SubQuery:
  470. privs, err := source.Statement.RequiredPrivileges()
  471. if err != nil {
  472. return nil, err
  473. }
  474. ep = append(ep, privs...)
  475. default:
  476. return nil, fmt.Errorf("invalid source: %s", source)
  477. }
  478. }
  479. return ep, nil
  480. }
  481. // IsSystemName returns true if name is an internal system name.
  482. func IsSystemName(name string) bool {
  483. switch name {
  484. case "_fieldKeys",
  485. "_measurements",
  486. "_name",
  487. "_series",
  488. "_tagKey",
  489. "_tagKeys",
  490. "_tags":
  491. return true
  492. default:
  493. return false
  494. }
  495. }
  496. // SortField represents a field to sort results by.
  497. type SortField struct {
  498. // Name of the field.
  499. Name string
  500. // Sort order.
  501. Ascending bool
  502. }
  503. // String returns a string representation of a sort field.
  504. func (field *SortField) String() string {
  505. var buf bytes.Buffer
  506. if field.Name != "" {
  507. _, _ = buf.WriteString(field.Name)
  508. _, _ = buf.WriteString(" ")
  509. }
  510. if field.Ascending {
  511. _, _ = buf.WriteString("ASC")
  512. } else {
  513. _, _ = buf.WriteString("DESC")
  514. }
  515. return buf.String()
  516. }
  517. // SortFields represents an ordered list of ORDER BY fields.
  518. type SortFields []*SortField
  519. // String returns a string representation of sort fields.
  520. func (a SortFields) String() string {
  521. fields := make([]string, 0, len(a))
  522. for _, field := range a {
  523. fields = append(fields, field.String())
  524. }
  525. return strings.Join(fields, ", ")
  526. }
  527. // CreateDatabaseStatement represents a command for creating a new database.
  528. type CreateDatabaseStatement struct {
  529. // Name of the database to be created.
  530. Name string
  531. // RetentionPolicyCreate indicates whether the user explicitly wants to create a retention policy.
  532. RetentionPolicyCreate bool
  533. // RetentionPolicyDuration indicates retention duration for the new database.
  534. RetentionPolicyDuration *time.Duration
  535. // RetentionPolicyReplication indicates retention replication for the new database.
  536. RetentionPolicyReplication *int
  537. // RetentionPolicyName indicates retention name for the new database.
  538. RetentionPolicyName string
  539. // RetentionPolicyShardGroupDuration indicates shard group duration for the new database.
  540. RetentionPolicyShardGroupDuration time.Duration
  541. }
  542. // String returns a string representation of the create database statement.
  543. func (s *CreateDatabaseStatement) String() string {
  544. var buf bytes.Buffer
  545. _, _ = buf.WriteString("CREATE DATABASE ")
  546. _, _ = buf.WriteString(QuoteIdent(s.Name))
  547. if s.RetentionPolicyCreate {
  548. _, _ = buf.WriteString(" WITH")
  549. if s.RetentionPolicyDuration != nil {
  550. _, _ = buf.WriteString(" DURATION ")
  551. _, _ = buf.WriteString(s.RetentionPolicyDuration.String())
  552. }
  553. if s.RetentionPolicyReplication != nil {
  554. _, _ = buf.WriteString(" REPLICATION ")
  555. _, _ = buf.WriteString(strconv.Itoa(*s.RetentionPolicyReplication))
  556. }
  557. if s.RetentionPolicyShardGroupDuration > 0 {
  558. _, _ = buf.WriteString(" SHARD DURATION ")
  559. _, _ = buf.WriteString(s.RetentionPolicyShardGroupDuration.String())
  560. }
  561. if s.RetentionPolicyName != "" {
  562. _, _ = buf.WriteString(" NAME ")
  563. _, _ = buf.WriteString(QuoteIdent(s.RetentionPolicyName))
  564. }
  565. }
  566. return buf.String()
  567. }
  568. // RequiredPrivileges returns the privilege required to execute a CreateDatabaseStatement.
  569. func (s *CreateDatabaseStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  570. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}, nil
  571. }
  572. // DropDatabaseStatement represents a command to drop a database.
  573. type DropDatabaseStatement struct {
  574. // Name of the database to be dropped.
  575. Name string
  576. }
  577. // String returns a string representation of the drop database statement.
  578. func (s *DropDatabaseStatement) String() string {
  579. var buf bytes.Buffer
  580. _, _ = buf.WriteString("DROP DATABASE ")
  581. _, _ = buf.WriteString(QuoteIdent(s.Name))
  582. return buf.String()
  583. }
  584. // RequiredPrivileges returns the privilege required to execute a DropDatabaseStatement.
  585. func (s *DropDatabaseStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  586. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}, nil
  587. }
  588. // DropRetentionPolicyStatement represents a command to drop a retention policy from a database.
  589. type DropRetentionPolicyStatement struct {
  590. // Name of the policy to drop.
  591. Name string
  592. // Name of the database to drop the policy from.
  593. Database string
  594. }
  595. // String returns a string representation of the drop retention policy statement.
  596. func (s *DropRetentionPolicyStatement) String() string {
  597. var buf bytes.Buffer
  598. _, _ = buf.WriteString("DROP RETENTION POLICY ")
  599. _, _ = buf.WriteString(QuoteIdent(s.Name))
  600. _, _ = buf.WriteString(" ON ")
  601. _, _ = buf.WriteString(QuoteIdent(s.Database))
  602. return buf.String()
  603. }
  604. // RequiredPrivileges returns the privilege required to execute a DropRetentionPolicyStatement.
  605. func (s *DropRetentionPolicyStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  606. return ExecutionPrivileges{{Admin: false, Name: s.Database, Privilege: WritePrivilege}}, nil
  607. }
  608. // DefaultDatabase returns the default database from the statement.
  609. func (s *DropRetentionPolicyStatement) DefaultDatabase() string {
  610. return s.Database
  611. }
  612. // CreateUserStatement represents a command for creating a new user.
  613. type CreateUserStatement struct {
  614. // Name of the user to be created.
  615. Name string
  616. // User's password.
  617. Password string
  618. // User's admin privilege.
  619. Admin bool
  620. }
  621. // String returns a string representation of the create user statement.
  622. func (s *CreateUserStatement) String() string {
  623. var buf bytes.Buffer
  624. _, _ = buf.WriteString("CREATE USER ")
  625. _, _ = buf.WriteString(QuoteIdent(s.Name))
  626. _, _ = buf.WriteString(" WITH PASSWORD ")
  627. _, _ = buf.WriteString("[REDACTED]")
  628. if s.Admin {
  629. _, _ = buf.WriteString(" WITH ALL PRIVILEGES")
  630. }
  631. return buf.String()
  632. }
  633. // RequiredPrivileges returns the privilege(s) required to execute a CreateUserStatement.
  634. func (s *CreateUserStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  635. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}, nil
  636. }
  637. // DropUserStatement represents a command for dropping a user.
  638. type DropUserStatement struct {
  639. // Name of the user to drop.
  640. Name string
  641. }
  642. // String returns a string representation of the drop user statement.
  643. func (s *DropUserStatement) String() string {
  644. var buf bytes.Buffer
  645. _, _ = buf.WriteString("DROP USER ")
  646. _, _ = buf.WriteString(QuoteIdent(s.Name))
  647. return buf.String()
  648. }
  649. // RequiredPrivileges returns the privilege(s) required to execute a DropUserStatement.
  650. func (s *DropUserStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  651. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}, nil
  652. }
  653. // Privilege is a type of action a user can be granted the right to use.
  654. type Privilege int
  655. const (
  656. // NoPrivileges means no privileges required / granted / revoked.
  657. NoPrivileges Privilege = iota
  658. // ReadPrivilege means read privilege required / granted / revoked.
  659. ReadPrivilege
  660. // WritePrivilege means write privilege required / granted / revoked.
  661. WritePrivilege
  662. // AllPrivileges means all privileges required / granted / revoked.
  663. AllPrivileges
  664. )
  665. // NewPrivilege returns an initialized *Privilege.
  666. func NewPrivilege(p Privilege) *Privilege { return &p }
  667. // String returns a string representation of a Privilege.
  668. func (p Privilege) String() string {
  669. switch p {
  670. case NoPrivileges:
  671. return "NO PRIVILEGES"
  672. case ReadPrivilege:
  673. return "READ"
  674. case WritePrivilege:
  675. return "WRITE"
  676. case AllPrivileges:
  677. return "ALL PRIVILEGES"
  678. }
  679. return ""
  680. }
  681. // GrantStatement represents a command for granting a privilege.
  682. type GrantStatement struct {
  683. // The privilege to be granted.
  684. Privilege Privilege
  685. // Database to grant the privilege to.
  686. On string
  687. // Who to grant the privilege to.
  688. User string
  689. }
  690. // String returns a string representation of the grant statement.
  691. func (s *GrantStatement) String() string {
  692. var buf bytes.Buffer
  693. _, _ = buf.WriteString("GRANT ")
  694. _, _ = buf.WriteString(s.Privilege.String())
  695. _, _ = buf.WriteString(" ON ")
  696. _, _ = buf.WriteString(QuoteIdent(s.On))
  697. _, _ = buf.WriteString(" TO ")
  698. _, _ = buf.WriteString(QuoteIdent(s.User))
  699. return buf.String()
  700. }
  701. // RequiredPrivileges returns the privilege required to execute a GrantStatement.
  702. func (s *GrantStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  703. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}, nil
  704. }
  705. // DefaultDatabase returns the default database from the statement.
  706. func (s *GrantStatement) DefaultDatabase() string {
  707. return s.On
  708. }
  709. // GrantAdminStatement represents a command for granting admin privilege.
  710. type GrantAdminStatement struct {
  711. // Who to grant the privilege to.
  712. User string
  713. }
  714. // String returns a string representation of the grant admin statement.
  715. func (s *GrantAdminStatement) String() string {
  716. var buf bytes.Buffer
  717. _, _ = buf.WriteString("GRANT ALL PRIVILEGES TO ")
  718. _, _ = buf.WriteString(QuoteIdent(s.User))
  719. return buf.String()
  720. }
  721. // RequiredPrivileges returns the privilege required to execute a GrantAdminStatement.
  722. func (s *GrantAdminStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  723. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}, nil
  724. }
  725. // KillQueryStatement represents a command for killing a query.
  726. type KillQueryStatement struct {
  727. // The query to kill.
  728. QueryID uint64
  729. // The host to delegate the kill to.
  730. Host string
  731. }
  732. // String returns a string representation of the kill query statement.
  733. func (s *KillQueryStatement) String() string {
  734. var buf bytes.Buffer
  735. _, _ = buf.WriteString("KILL QUERY ")
  736. _, _ = buf.WriteString(strconv.FormatUint(s.QueryID, 10))
  737. if s.Host != "" {
  738. _, _ = buf.WriteString(" ON ")
  739. _, _ = buf.WriteString(QuoteIdent(s.Host))
  740. }
  741. return buf.String()
  742. }
  743. // RequiredPrivileges returns the privilege required to execute a KillQueryStatement.
  744. func (s *KillQueryStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  745. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}, nil
  746. }
  747. // SetPasswordUserStatement represents a command for changing user password.
  748. type SetPasswordUserStatement struct {
  749. // Plain-text password.
  750. Password string
  751. // Who to grant the privilege to.
  752. Name string
  753. }
  754. // String returns a string representation of the set password statement.
  755. func (s *SetPasswordUserStatement) String() string {
  756. var buf bytes.Buffer
  757. _, _ = buf.WriteString("SET PASSWORD FOR ")
  758. _, _ = buf.WriteString(QuoteIdent(s.Name))
  759. _, _ = buf.WriteString(" = ")
  760. _, _ = buf.WriteString("[REDACTED]")
  761. return buf.String()
  762. }
  763. // RequiredPrivileges returns the privilege required to execute a SetPasswordUserStatement.
  764. func (s *SetPasswordUserStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  765. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}, nil
  766. }
  767. // RevokeStatement represents a command to revoke a privilege from a user.
  768. type RevokeStatement struct {
  769. // The privilege to be revoked.
  770. Privilege Privilege
  771. // Database to revoke the privilege from.
  772. On string
  773. // Who to revoke privilege from.
  774. User string
  775. }
  776. // String returns a string representation of the revoke statement.
  777. func (s *RevokeStatement) String() string {
  778. var buf bytes.Buffer
  779. _, _ = buf.WriteString("REVOKE ")
  780. _, _ = buf.WriteString(s.Privilege.String())
  781. _, _ = buf.WriteString(" ON ")
  782. _, _ = buf.WriteString(QuoteIdent(s.On))
  783. _, _ = buf.WriteString(" FROM ")
  784. _, _ = buf.WriteString(QuoteIdent(s.User))
  785. return buf.String()
  786. }
  787. // RequiredPrivileges returns the privilege required to execute a RevokeStatement.
  788. func (s *RevokeStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  789. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}, nil
  790. }
  791. // DefaultDatabase returns the default database from the statement.
  792. func (s *RevokeStatement) DefaultDatabase() string {
  793. return s.On
  794. }
  795. // RevokeAdminStatement represents a command to revoke admin privilege from a user.
  796. type RevokeAdminStatement struct {
  797. // Who to revoke admin privilege from.
  798. User string
  799. }
  800. // String returns a string representation of the revoke admin statement.
  801. func (s *RevokeAdminStatement) String() string {
  802. var buf bytes.Buffer
  803. _, _ = buf.WriteString("REVOKE ALL PRIVILEGES FROM ")
  804. _, _ = buf.WriteString(QuoteIdent(s.User))
  805. return buf.String()
  806. }
  807. // RequiredPrivileges returns the privilege required to execute a RevokeAdminStatement.
  808. func (s *RevokeAdminStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  809. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}, nil
  810. }
  811. // CreateRetentionPolicyStatement represents a command to create a retention policy.
  812. type CreateRetentionPolicyStatement struct {
  813. // Name of policy to create.
  814. Name string
  815. // Name of database this policy belongs to.
  816. Database string
  817. // Duration data written to this policy will be retained.
  818. Duration time.Duration
  819. // Replication factor for data written to this policy.
  820. Replication int
  821. // Should this policy be set as default for the database?
  822. Default bool
  823. // Shard Duration.
  824. ShardGroupDuration time.Duration
  825. }
  826. // String returns a string representation of the create retention policy.
  827. func (s *CreateRetentionPolicyStatement) String() string {
  828. var buf bytes.Buffer
  829. _, _ = buf.WriteString("CREATE RETENTION POLICY ")
  830. _, _ = buf.WriteString(QuoteIdent(s.Name))
  831. _, _ = buf.WriteString(" ON ")
  832. _, _ = buf.WriteString(QuoteIdent(s.Database))
  833. _, _ = buf.WriteString(" DURATION ")
  834. _, _ = buf.WriteString(FormatDuration(s.Duration))
  835. _, _ = buf.WriteString(" REPLICATION ")
  836. _, _ = buf.WriteString(strconv.Itoa(s.Replication))
  837. if s.ShardGroupDuration > 0 {
  838. _, _ = buf.WriteString(" SHARD DURATION ")
  839. _, _ = buf.WriteString(FormatDuration(s.ShardGroupDuration))
  840. }
  841. if s.Default {
  842. _, _ = buf.WriteString(" DEFAULT")
  843. }
  844. return buf.String()
  845. }
  846. // RequiredPrivileges returns the privilege required to execute a CreateRetentionPolicyStatement.
  847. func (s *CreateRetentionPolicyStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  848. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}, nil
  849. }
  850. // DefaultDatabase returns the default database from the statement.
  851. func (s *CreateRetentionPolicyStatement) DefaultDatabase() string {
  852. return s.Database
  853. }
  854. // AlterRetentionPolicyStatement represents a command to alter an existing retention policy.
  855. type AlterRetentionPolicyStatement struct {
  856. // Name of policy to alter.
  857. Name string
  858. // Name of the database this policy belongs to.
  859. Database string
  860. // Duration data written to this policy will be retained.
  861. Duration *time.Duration
  862. // Replication factor for data written to this policy.
  863. Replication *int
  864. // Should this policy be set as defalut for the database?
  865. Default bool
  866. // Duration of the Shard.
  867. ShardGroupDuration *time.Duration
  868. }
  869. // String returns a string representation of the alter retention policy statement.
  870. func (s *AlterRetentionPolicyStatement) String() string {
  871. var buf bytes.Buffer
  872. _, _ = buf.WriteString("ALTER RETENTION POLICY ")
  873. _, _ = buf.WriteString(QuoteIdent(s.Name))
  874. _, _ = buf.WriteString(" ON ")
  875. _, _ = buf.WriteString(QuoteIdent(s.Database))
  876. if s.Duration != nil {
  877. _, _ = buf.WriteString(" DURATION ")
  878. _, _ = buf.WriteString(FormatDuration(*s.Duration))
  879. }
  880. if s.Replication != nil {
  881. _, _ = buf.WriteString(" REPLICATION ")
  882. _, _ = buf.WriteString(strconv.Itoa(*s.Replication))
  883. }
  884. if s.ShardGroupDuration != nil {
  885. _, _ = buf.WriteString(" SHARD DURATION ")
  886. _, _ = buf.WriteString(FormatDuration(*s.ShardGroupDuration))
  887. }
  888. if s.Default {
  889. _, _ = buf.WriteString(" DEFAULT")
  890. }
  891. return buf.String()
  892. }
  893. // RequiredPrivileges returns the privilege required to execute an AlterRetentionPolicyStatement.
  894. func (s *AlterRetentionPolicyStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  895. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}, nil
  896. }
  897. // DefaultDatabase returns the default database from the statement.
  898. func (s *AlterRetentionPolicyStatement) DefaultDatabase() string {
  899. return s.Database
  900. }
  901. // FillOption represents different options for filling aggregate windows.
  902. type FillOption int
  903. const (
  904. // NullFill means that empty aggregate windows will just have null values.
  905. NullFill FillOption = iota
  906. // NoFill means that empty aggregate windows will be purged from the result.
  907. NoFill
  908. // NumberFill means that empty aggregate windows will be filled with a provided number.
  909. NumberFill
  910. // PreviousFill means that empty aggregate windows will be filled with whatever the previous aggregate window had.
  911. PreviousFill
  912. // LinearFill means that empty aggregate windows will be filled with whatever a linear value between non null windows.
  913. LinearFill
  914. )
  915. // SelectStatement represents a command for extracting data from the database.
  916. type SelectStatement struct {
  917. // Expressions returned from the selection.
  918. Fields Fields
  919. // Target (destination) for the result of a SELECT INTO query.
  920. Target *Target
  921. // Expressions used for grouping the selection.
  922. Dimensions Dimensions
  923. // Data sources (measurements) that fields are extracted from.
  924. Sources Sources
  925. // An expression evaluated on data point.
  926. Condition Expr
  927. // Fields to sort results by.
  928. SortFields SortFields
  929. // Maximum number of rows to be returned. Unlimited if zero.
  930. Limit int
  931. // Returns rows starting at an offset from the first row.
  932. Offset int
  933. // Maxiumum number of series to be returned. Unlimited if zero.
  934. SLimit int
  935. // Returns series starting at an offset from the first one.
  936. SOffset int
  937. // Memoized group by interval from GroupBy().
  938. groupByInterval time.Duration
  939. // Whether it's a query for raw data values (i.e. not an aggregate).
  940. IsRawQuery bool
  941. // What fill option the select statement uses, if any.
  942. Fill FillOption
  943. // The value to fill empty aggregate buckets with, if any.
  944. FillValue interface{}
  945. // The timezone for the query, if any.
  946. Location *time.Location
  947. // Renames the implicit time field name.
  948. TimeAlias string
  949. // Removes the "time" column from the output.
  950. OmitTime bool
  951. // Removes measurement name from resulting query. Useful for meta queries.
  952. StripName bool
  953. // Overrides the output measurement name.
  954. EmitName string
  955. // Removes duplicate rows from raw queries.
  956. Dedupe bool
  957. }
  958. // TimeAscending returns true if the time field is sorted in chronological order.
  959. func (s *SelectStatement) TimeAscending() bool {
  960. return len(s.SortFields) == 0 || s.SortFields[0].Ascending
  961. }
  962. // TimeFieldName returns the name of the time field.
  963. func (s *SelectStatement) TimeFieldName() string {
  964. if s.TimeAlias != "" {
  965. return s.TimeAlias
  966. }
  967. return "time"
  968. }
  969. // Clone returns a deep copy of the statement.
  970. func (s *SelectStatement) Clone() *SelectStatement {
  971. clone := *s
  972. clone.Fields = make(Fields, 0, len(s.Fields))
  973. clone.Dimensions = make(Dimensions, 0, len(s.Dimensions))
  974. clone.Sources = cloneSources(s.Sources)
  975. clone.SortFields = make(SortFields, 0, len(s.SortFields))
  976. clone.Condition = CloneExpr(s.Condition)
  977. if s.Target != nil {
  978. clone.Target = &Target{
  979. Measurement: &Measurement{
  980. Database: s.Target.Measurement.Database,
  981. RetentionPolicy: s.Target.Measurement.RetentionPolicy,
  982. Name: s.Target.Measurement.Name,
  983. Regex: CloneRegexLiteral(s.Target.Measurement.Regex),
  984. },
  985. }
  986. }
  987. for _, f := range s.Fields {
  988. clone.Fields = append(clone.Fields, &Field{Expr: CloneExpr(f.Expr), Alias: f.Alias})
  989. }
  990. for _, d := range s.Dimensions {
  991. clone.Dimensions = append(clone.Dimensions, &Dimension{Expr: CloneExpr(d.Expr)})
  992. }
  993. for _, f := range s.SortFields {
  994. clone.SortFields = append(clone.SortFields, &SortField{Name: f.Name, Ascending: f.Ascending})
  995. }
  996. return &clone
  997. }
  998. func cloneSources(sources Sources) Sources {
  999. clone := make(Sources, 0, len(sources))
  1000. for _, s := range sources {
  1001. clone = append(clone, cloneSource(s))
  1002. }
  1003. return clone
  1004. }
  1005. func cloneSource(s Source) Source {
  1006. if s == nil {
  1007. return nil
  1008. }
  1009. switch s := s.(type) {
  1010. case *Measurement:
  1011. return s.Clone()
  1012. case *SubQuery:
  1013. return &SubQuery{Statement: s.Statement.Clone()}
  1014. default:
  1015. panic("unreachable")
  1016. }
  1017. }
  1018. // FieldMapper returns the data type for the field inside of the measurement.
  1019. type FieldMapper interface {
  1020. FieldDimensions(m *Measurement) (fields map[string]DataType, dimensions map[string]struct{}, err error)
  1021. TypeMapper
  1022. }
  1023. // RewriteFields returns the re-written form of the select statement. Any wildcard query
  1024. // fields are replaced with the supplied fields, and any wildcard GROUP BY fields are replaced
  1025. // with the supplied dimensions. Any fields with no type specifier are rewritten with the
  1026. // appropriate type.
  1027. func (s *SelectStatement) RewriteFields(m FieldMapper) (*SelectStatement, error) {
  1028. // Clone the statement so we aren't rewriting the original.
  1029. other := s.Clone()
  1030. // Iterate through the sources and rewrite any subqueries first.
  1031. for _, src := range other.Sources {
  1032. switch src := src.(type) {
  1033. case *SubQuery:
  1034. stmt, err := src.Statement.RewriteFields(m)
  1035. if err != nil {
  1036. return nil, err
  1037. }
  1038. src.Statement = stmt
  1039. }
  1040. }
  1041. // Rewrite all variable references in the fields with their types if one
  1042. // hasn't been specified.
  1043. rewrite := func(n Node) {
  1044. ref, ok := n.(*VarRef)
  1045. if !ok || (ref.Type != Unknown && ref.Type != AnyField) {
  1046. return
  1047. }
  1048. typ := EvalType(ref, other.Sources, m)
  1049. if typ == Tag && ref.Type == AnyField {
  1050. return
  1051. }
  1052. ref.Type = typ
  1053. }
  1054. WalkFunc(other.Fields, rewrite)
  1055. WalkFunc(other.Condition, rewrite)
  1056. // Ignore if there are no wildcards.
  1057. hasFieldWildcard := other.HasFieldWildcard()
  1058. hasDimensionWildcard := other.HasDimensionWildcard()
  1059. if !hasFieldWildcard && !hasDimensionWildcard {
  1060. return other, nil
  1061. }
  1062. fieldSet, dimensionSet, err := FieldDimensions(other.Sources, m)
  1063. if err != nil {
  1064. return nil, err
  1065. }
  1066. // If there are no dimension wildcards then merge dimensions to fields.
  1067. if !hasDimensionWildcard {
  1068. // Remove the dimensions present in the group by so they don't get added as fields.
  1069. for _, d := range other.Dimensions {
  1070. switch expr := d.Expr.(type) {
  1071. case *VarRef:
  1072. delete(dimensionSet, expr.Val)
  1073. }
  1074. }
  1075. }
  1076. // Sort the field and dimension names for wildcard expansion.
  1077. var fields []VarRef
  1078. if len(fieldSet) > 0 {
  1079. fields = make([]VarRef, 0, len(fieldSet))
  1080. for name, typ := range fieldSet {
  1081. fields = append(fields, VarRef{Val: name, Type: typ})
  1082. }
  1083. if !hasDimensionWildcard {
  1084. for name := range dimensionSet {
  1085. fields = append(fields, VarRef{Val: name, Type: Tag})
  1086. }
  1087. dimensionSet = nil
  1088. }
  1089. sort.Sort(VarRefs(fields))
  1090. }
  1091. dimensions := stringSetSlice(dimensionSet)
  1092. // Rewrite all wildcard query fields
  1093. if hasFieldWildcard {
  1094. // Allocate a slice assuming there is exactly one wildcard for efficiency.
  1095. rwFields := make(Fields, 0, len(other.Fields)+len(fields)-1)
  1096. for _, f := range other.Fields {
  1097. switch expr := f.Expr.(type) {
  1098. case *Wildcard:
  1099. for _, ref := range fields {
  1100. if expr.Type == FIELD && ref.Type == Tag {
  1101. continue
  1102. } else if expr.Type == TAG && ref.Type != Tag {
  1103. continue
  1104. }
  1105. rwFields = append(rwFields, &Field{Expr: &VarRef{Val: ref.Val, Type: ref.Type}})
  1106. }
  1107. case *RegexLiteral:
  1108. for _, ref := range fields {
  1109. if expr.Val.MatchString(ref.Val) {
  1110. rwFields = append(rwFields, &Field{Expr: &VarRef{Val: ref.Val, Type: ref.Type}})
  1111. }
  1112. }
  1113. case *Call:
  1114. // Clone a template that we can modify and use for new fields.
  1115. template := CloneExpr(expr).(*Call)
  1116. // Search for the call with a wildcard by continuously descending until
  1117. // we no longer have a call.
  1118. call := template
  1119. for len(call.Args) > 0 {
  1120. arg, ok := call.Args[0].(*Call)
  1121. if !ok {
  1122. break
  1123. }
  1124. call = arg
  1125. }
  1126. // Check if this field value is a wildcard.
  1127. if len(call.Args) == 0 {
  1128. rwFields = append(rwFields, f)
  1129. continue
  1130. }
  1131. // Retrieve if this is a wildcard or a regular expression.
  1132. var re *regexp.Regexp
  1133. switch expr := call.Args[0].(type) {
  1134. case *Wildcard:
  1135. if expr.Type == TAG {
  1136. return nil, fmt.Errorf("unable to use tag wildcard in %s()", call.Name)
  1137. }
  1138. case *RegexLiteral:
  1139. re = expr.Val
  1140. default:
  1141. rwFields = append(rwFields, f)
  1142. continue
  1143. }
  1144. // All types that can expand wildcards support float, integer, and unsigned.
  1145. supportedTypes := map[DataType]struct{}{
  1146. Float: {},
  1147. Integer: {},
  1148. Unsigned: {},
  1149. }
  1150. // Add additional types for certain functions.
  1151. switch call.Name {
  1152. case "count", "first", "last", "distinct", "elapsed", "mode", "sample":
  1153. supportedTypes[String] = struct{}{}
  1154. fallthrough
  1155. case "min", "max":
  1156. supportedTypes[Boolean] = struct{}{}
  1157. case "holt_winters", "holt_winters_with_fit":
  1158. delete(supportedTypes, Unsigned)
  1159. }
  1160. for _, ref := range fields {
  1161. // Do not expand tags within a function call. It likely won't do anything
  1162. // anyway and will be the wrong thing in 99% of cases.
  1163. if ref.Type == Tag {
  1164. continue
  1165. } else if _, ok := supportedTypes[ref.Type]; !ok {
  1166. continue
  1167. } else if re != nil && !re.MatchString(ref.Val) {
  1168. continue
  1169. }
  1170. // Make a new expression and replace the wildcard within this cloned expression.
  1171. call.Args[0] = &VarRef{Val: ref.Val, Type: ref.Type}
  1172. rwFields = append(rwFields, &Field{
  1173. Expr: CloneExpr(template),
  1174. Alias: fmt.Sprintf("%s_%s", f.Name(), ref.Val),
  1175. })
  1176. }
  1177. case *BinaryExpr:
  1178. // Search for regexes or wildcards within the binary
  1179. // expression. If we find any, throw an error indicating that
  1180. // it's illegal.
  1181. var regex, wildcard bool
  1182. WalkFunc(expr, func(n Node) {
  1183. switch n.(type) {
  1184. case *RegexLiteral:
  1185. regex = true
  1186. case *Wildcard:
  1187. wildcard = true
  1188. }
  1189. })
  1190. if wildcard {
  1191. return nil, fmt.Errorf("unsupported expression with wildcard: %s", f.Expr)
  1192. } else if regex {
  1193. return nil, fmt.Errorf("unsupported expression with regex field: %s", f.Expr)
  1194. }
  1195. rwFields = append(rwFields, f)
  1196. default:
  1197. rwFields = append(rwFields, f)
  1198. }
  1199. }
  1200. other.Fields = rwFields
  1201. }
  1202. // Rewrite all wildcard GROUP BY fields
  1203. if hasDimensionWildcard {
  1204. // Allocate a slice assuming there is exactly one wildcard for efficiency.
  1205. rwDimensions := make(Dimensions, 0, len(other.Dimensions)+len(dimensions)-1)
  1206. for _, d := range other.Dimensions {
  1207. switch expr := d.Expr.(type) {
  1208. case *Wildcard:
  1209. for _, name := range dimensions {
  1210. rwDimensions = append(rwDimensions, &Dimension{Expr: &VarRef{Val: name}})
  1211. }
  1212. case *RegexLiteral:
  1213. for _, name := range dimensions {
  1214. if expr.Val.MatchString(name) {
  1215. rwDimensions = append(rwDimensions, &Dimension{Expr: &VarRef{Val: name}})
  1216. }
  1217. }
  1218. default:
  1219. rwDimensions = append(rwDimensions, d)
  1220. }
  1221. }
  1222. other.Dimensions = rwDimensions
  1223. }
  1224. return other, nil
  1225. }
  1226. // RewriteRegexConditions rewrites regex conditions to make better use of the
  1227. // database index.
  1228. //
  1229. // Conditions that can currently be simplified are:
  1230. //
  1231. // - host =~ /^foo$/ becomes host = 'foo'
  1232. // - host !~ /^foo$/ becomes host != 'foo'
  1233. //
  1234. // Note: if the regex contains groups, character classes, repetition or
  1235. // similar, it's likely it won't be rewritten. In order to support rewriting
  1236. // regexes with these characters would be a lot more work.
  1237. func (s *SelectStatement) RewriteRegexConditions() {
  1238. s.Condition = RewriteExpr(s.Condition, func(e Expr) Expr {
  1239. be, ok := e.(*BinaryExpr)
  1240. if !ok || (be.Op != EQREGEX && be.Op != NEQREGEX) {
  1241. // This expression is not a binary condition or doesn't have a
  1242. // regex based operator.
  1243. return e
  1244. }
  1245. // Handle regex-based condition.
  1246. rhs := be.RHS.(*RegexLiteral) // This must be a regex.
  1247. vals, ok := matchExactRegex(rhs.Val.String())
  1248. if !ok {
  1249. // Regex didn't match.
  1250. return e
  1251. }
  1252. // Update the condition operator.
  1253. var concatOp Token
  1254. if be.Op == EQREGEX {
  1255. be.Op = EQ
  1256. concatOp = OR
  1257. } else {
  1258. be.Op = NEQ
  1259. concatOp = AND
  1260. }
  1261. // Remove leading and trailing ^ and $.
  1262. switch {
  1263. case len(vals) == 0:
  1264. be.RHS = &StringLiteral{}
  1265. case len(vals) == 1:
  1266. be.RHS = &StringLiteral{Val: vals[0]}
  1267. default:
  1268. expr := &BinaryExpr{
  1269. Op: be.Op,
  1270. LHS: be.LHS,
  1271. RHS: &StringLiteral{Val: vals[0]},
  1272. }
  1273. for i := 1; i < len(vals); i++ {
  1274. expr = &BinaryExpr{
  1275. Op: concatOp,
  1276. LHS: expr,
  1277. RHS: &BinaryExpr{
  1278. Op: be.Op,
  1279. LHS: be.LHS,
  1280. RHS: &StringLiteral{Val: vals[i]},
  1281. },
  1282. }
  1283. }
  1284. return &ParenExpr{Expr: expr}
  1285. }
  1286. return be
  1287. })
  1288. // Unwrap any top level parenthesis.
  1289. if cond, ok := s.Condition.(*ParenExpr); ok {
  1290. s.Condition = cond.Expr
  1291. }
  1292. }
  1293. // matchExactRegex matches regexes into literals if possible. This will match the
  1294. // pattern /^foo$/ or /^(foo|bar)$/. It considers /^$/ to be a matching regex.
  1295. func matchExactRegex(v string) ([]string, bool) {
  1296. re, err := syntax.Parse(v, syntax.Perl)
  1297. if err != nil {
  1298. // Nothing we can do or log.
  1299. return nil, false
  1300. }
  1301. re = re.Simplify()
  1302. if re.Op != syntax.OpConcat {
  1303. return nil, false
  1304. }
  1305. if len(re.Sub) < 2 {
  1306. // Regex has too few subexpressions.
  1307. return nil, false
  1308. }
  1309. start := re.Sub[0]
  1310. if !(start.Op == syntax.OpBeginLine || start.Op == syntax.OpBeginText) {
  1311. // Regex does not begin with ^
  1312. return nil, false
  1313. }
  1314. end := re.Sub[len(re.Sub)-1]
  1315. if !(end.Op == syntax.OpEndLine || end.Op == syntax.OpEndText) {
  1316. // Regex does not end with $
  1317. return nil, false
  1318. }
  1319. // Remove the begin and end text from the regex.
  1320. re.Sub = re.Sub[1 : len(re.Sub)-1]
  1321. if len(re.Sub) == 0 {
  1322. // The regex /^$/
  1323. return nil, true
  1324. }
  1325. return matchRegex(re)
  1326. }
  1327. // matchRegex will match a regular expression to literals if possible.
  1328. func matchRegex(re *syntax.Regexp) ([]string, bool) {
  1329. // Maximum number of literals that the expression should be expanded to. If
  1330. // this is exceeded, no expansion will be done. This allows reasonable
  1331. // optimizations of regex by expansion to literals but prevents cases
  1332. // where that expansion would result in a large number of literals.
  1333. const maxLiterals = 100
  1334. // Exit if we see a case-insensitive flag as it is not something we support at this time.
  1335. if re.Flags&syntax.FoldCase != 0 {
  1336. return nil, false
  1337. }
  1338. switch re.Op {
  1339. case syntax.OpLiteral:
  1340. // We can rewrite this regex.
  1341. return []string{string(re.Rune)}, true
  1342. case syntax.OpCapture:
  1343. return matchRegex(re.Sub[0])
  1344. case syntax.OpConcat:
  1345. // Go through each of the subs and concatenate the result to each one.
  1346. names, ok := matchRegex(re.Sub[0])
  1347. if !ok {
  1348. return nil, false
  1349. }
  1350. for _, sub := range re.Sub[1:] {
  1351. vals, ok := matchRegex(sub)
  1352. if !ok {
  1353. return nil, false
  1354. }
  1355. // If there is only one value, concatenate it to all strings rather
  1356. // than allocate a new slice.
  1357. if len(vals) == 1 {
  1358. for i := range names {
  1359. names[i] += vals[0]
  1360. }
  1361. continue
  1362. } else if len(names) == 1 {
  1363. // If there is only one value, then do this concatenation in
  1364. // the opposite direction.
  1365. for i := range vals {
  1366. vals[i] = names[0] + vals[i]
  1367. }
  1368. names = vals
  1369. continue
  1370. }
  1371. sz := len(names) * len(vals)
  1372. if sz > maxLiterals {
  1373. return nil, false
  1374. }
  1375. // The long method of using multiple concatenations.
  1376. concat := make([]string, sz)
  1377. for i := range names {
  1378. for j := range vals {
  1379. concat[i*len(vals)+j] = names[i] + vals[j]
  1380. }
  1381. }
  1382. names = concat
  1383. }
  1384. return names, true
  1385. case syntax.OpCharClass:
  1386. var sz int
  1387. for i := 0; i < len(re.Rune); i += 2 {
  1388. sz += int(re.Rune[i+1]) - int(re.Rune[i]) + 1
  1389. }
  1390. if sz > maxLiterals {
  1391. return nil, false
  1392. }
  1393. names := make([]string, 0, sz)
  1394. for i := 0; i < len(re.Rune); i += 2 {
  1395. for r := int(re.Rune[i]); r <= int(re.Rune[i+1]); r++ {
  1396. names = append(names, string([]rune{rune(r)}))
  1397. }
  1398. }
  1399. return names, true
  1400. case syntax.OpAlternate:
  1401. var names []string
  1402. for _, sub := range re.Sub {
  1403. vals, ok := matchRegex(sub)
  1404. if !ok {
  1405. return nil, false
  1406. }
  1407. names = append(names, vals...)
  1408. }
  1409. if len(names) > maxLiterals {
  1410. return nil, false
  1411. }
  1412. return names, true
  1413. }
  1414. return nil, false
  1415. }
  1416. // RewriteDistinct rewrites the expression to be a call for map/reduce to work correctly.
  1417. // This method assumes all validation has passed.
  1418. func (s *SelectStatement) RewriteDistinct() {
  1419. WalkFunc(s.Fields, func(n Node) {
  1420. switch n := n.(type) {
  1421. case *Field:
  1422. if expr, ok := n.Expr.(*Distinct); ok {
  1423. n.Expr = expr.NewCall()
  1424. s.IsRawQuery = false
  1425. }
  1426. case *Call:
  1427. for i, arg := range n.Args {
  1428. if arg, ok := arg.(*Distinct); ok {
  1429. n.Args[i] = arg.NewCall()
  1430. }
  1431. }
  1432. }
  1433. })
  1434. }
  1435. // RewriteTimeFields removes any "time" field references.
  1436. func (s *SelectStatement) RewriteTimeFields() {
  1437. for i := 0; i < len(s.Fields); i++ {
  1438. switch expr := s.Fields[i].Expr.(type) {
  1439. case *VarRef:
  1440. if expr.Val == "time" {
  1441. s.TimeAlias = s.Fields[i].Alias
  1442. s.Fields = append(s.Fields[:i], s.Fields[i+1:]...)
  1443. }
  1444. }
  1445. }
  1446. }
  1447. // ColumnNames will walk all fields and functions and return the appropriate field names for the select statement
  1448. // while maintaining order of the field names.
  1449. func (s *SelectStatement) ColumnNames() []string {
  1450. // First walk each field to determine the number of columns.
  1451. columnFields := Fields{}
  1452. for _, field := range s.Fields {
  1453. columnFields = append(columnFields, field)
  1454. switch f := field.Expr.(type) {
  1455. case *Call:
  1456. if s.Target == nil && (f.Name == "top" || f.Name == "bottom") {
  1457. for _, arg := range f.Args[1:] {
  1458. ref, ok := arg.(*VarRef)
  1459. if ok {
  1460. columnFields = append(columnFields, &Field{Expr: ref})
  1461. }
  1462. }
  1463. }
  1464. }
  1465. }
  1466. // Determine if we should add an extra column for an implicit time.
  1467. offset := 0
  1468. if !s.OmitTime {
  1469. offset++
  1470. }
  1471. columnNames := make([]string, len(columnFields)+offset)
  1472. if !s.OmitTime {
  1473. // Add the implicit time if requested.
  1474. columnNames[0] = s.TimeFieldName()
  1475. }
  1476. // Keep track of the encountered column names.
  1477. names := make(map[string]int)
  1478. // Resolve aliases first.
  1479. for i, col := range columnFields {
  1480. if col.Alias != "" {
  1481. columnNames[i+offset] = col.Alias
  1482. names[col.Alias] = 1
  1483. }
  1484. }
  1485. // Resolve any generated names and resolve conflicts.
  1486. for i, col := range columnFields {
  1487. if columnNames[i+offset] != "" {
  1488. continue
  1489. }
  1490. name := col.Name()
  1491. count, conflict := names[name]
  1492. if conflict {
  1493. for {
  1494. resolvedName := fmt.Sprintf("%s_%d", name, count)
  1495. _, conflict = names[resolvedName]
  1496. if !conflict {
  1497. names[name] = count + 1
  1498. name = resolvedName
  1499. break
  1500. }
  1501. count++
  1502. }
  1503. }
  1504. names[name]++
  1505. columnNames[i+offset] = name
  1506. }
  1507. return columnNames
  1508. }
  1509. // FieldExprByName returns the expression that matches the field name and the
  1510. // index where this was found. If the name matches one of the arguments to
  1511. // "top" or "bottom", the variable reference inside of the function is returned
  1512. // and the index is of the function call rather than the variable reference.
  1513. // If no expression is found, -1 is returned for the index and the expression
  1514. // will be nil.
  1515. func (s *SelectStatement) FieldExprByName(name string) (int, Expr) {
  1516. for i, f := range s.Fields {
  1517. if f.Name() == name {
  1518. return i, f.Expr
  1519. } else if call, ok := f.Expr.(*Call); ok && (call.Name == "top" || call.Name == "bottom") && len(call.Args) > 2 {
  1520. for _, arg := range call.Args[1 : len(call.Args)-1] {
  1521. if arg, ok := arg.(*VarRef); ok && arg.Val == name {
  1522. return i, arg
  1523. }
  1524. }
  1525. }
  1526. }
  1527. return -1, nil
  1528. }
  1529. // Reduce calls the Reduce function on the different components of the
  1530. // SelectStatement to reduce the statement.
  1531. func (s *SelectStatement) Reduce(valuer Valuer) *SelectStatement {
  1532. stmt := s.Clone()
  1533. stmt.Condition = Reduce(stmt.Condition, valuer)
  1534. for _, d := range stmt.Dimensions {
  1535. d.Expr = Reduce(d.Expr, valuer)
  1536. }
  1537. for _, source := range stmt.Sources {
  1538. switch source := source.(type) {
  1539. case *SubQuery:
  1540. source.Statement = source.Statement.Reduce(valuer)
  1541. }
  1542. }
  1543. return stmt
  1544. }
  1545. // String returns a string representation of the select statement.
  1546. func (s *SelectStatement) String() string {
  1547. var buf bytes.Buffer
  1548. _, _ = buf.WriteString("SELECT ")
  1549. _, _ = buf.WriteString(s.Fields.String())
  1550. if s.Target != nil {
  1551. _, _ = buf.WriteString(" ")
  1552. _, _ = buf.WriteString(s.Target.String())
  1553. }
  1554. if len(s.Sources) > 0 {
  1555. _, _ = buf.WriteString(" FROM ")
  1556. _, _ = buf.WriteString(s.Sources.String())
  1557. }
  1558. if s.Condition != nil {
  1559. _, _ = buf.WriteString(" WHERE ")
  1560. _, _ = buf.WriteString(s.Condition.String())
  1561. }
  1562. if len(s.Dimensions) > 0 {
  1563. _, _ = buf.WriteString(" GROUP BY ")
  1564. _, _ = buf.WriteString(s.Dimensions.String())
  1565. }
  1566. switch s.Fill {
  1567. case NoFill:
  1568. _, _ = buf.WriteString(" fill(none)")
  1569. case NumberFill:
  1570. _, _ = buf.WriteString(fmt.Sprintf(" fill(%v)", s.FillValue))
  1571. case LinearFill:
  1572. _, _ = buf.WriteString(" fill(linear)")
  1573. case PreviousFill:
  1574. _, _ = buf.WriteString(" fill(previous)")
  1575. }
  1576. if len(s.SortFields) > 0 {
  1577. _, _ = buf.WriteString(" ORDER BY ")
  1578. _, _ = buf.WriteString(s.SortFields.String())
  1579. }
  1580. if s.Limit > 0 {
  1581. _, _ = fmt.Fprintf(&buf, " LIMIT %d", s.Limit)
  1582. }
  1583. if s.Offset > 0 {
  1584. _, _ = buf.WriteString(" OFFSET ")
  1585. _, _ = buf.WriteString(strconv.Itoa(s.Offset))
  1586. }
  1587. if s.SLimit > 0 {
  1588. _, _ = fmt.Fprintf(&buf, " SLIMIT %d", s.SLimit)
  1589. }
  1590. if s.SOffset > 0 {
  1591. _, _ = fmt.Fprintf(&buf, " SOFFSET %d", s.SOffset)
  1592. }
  1593. if s.Location != nil {
  1594. _, _ = fmt.Fprintf(&buf, ` TZ('%s')`, s.Location)
  1595. }
  1596. return buf.String()
  1597. }
  1598. // RequiredPrivileges returns the privilege required to execute the SelectStatement.
  1599. // NOTE: Statement should be normalized first (database name(s) in Sources and
  1600. // Target should be populated). If the statement has not been normalized, an
  1601. // empty string will be returned for the database name and it is up to the caller
  1602. // to interpret that as the default database.
  1603. func (s *SelectStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  1604. ep, err := s.Sources.RequiredPrivileges()
  1605. if err != nil {
  1606. return nil, err
  1607. }
  1608. if s.Target != nil {
  1609. ep = append(ep, ExecutionPrivilege{Admin: false, Name: s.Target.Measurement.Database, Privilege: WritePrivilege})
  1610. }
  1611. return ep, nil
  1612. }
  1613. // HasWildcard returns whether or not the select statement has at least 1 wildcard.
  1614. func (s *SelectStatement) HasWildcard() bool {
  1615. return s.HasFieldWildcard() || s.HasDimensionWildcard()
  1616. }
  1617. // HasFieldWildcard returns whether or not the select statement has at least 1 wildcard in the fields.
  1618. func (s *SelectStatement) HasFieldWildcard() (hasWildcard bool) {
  1619. WalkFunc(s.Fields, func(n Node) {
  1620. if hasWildcard {
  1621. return
  1622. }
  1623. switch n.(type) {
  1624. case *Wildcard, *RegexLiteral:
  1625. hasWildcard = true
  1626. }
  1627. })
  1628. return hasWildcard
  1629. }
  1630. // HasDimensionWildcard returns whether or not the select statement has
  1631. // at least 1 wildcard in the dimensions aka `GROUP BY`.
  1632. func (s *SelectStatement) HasDimensionWildcard() bool {
  1633. for _, d := range s.Dimensions {
  1634. switch d.Expr.(type) {
  1635. case *Wildcard, *RegexLiteral:
  1636. return true
  1637. }
  1638. }
  1639. return false
  1640. }
  1641. // GroupByInterval extracts the time interval, if specified.
  1642. func (s *SelectStatement) GroupByInterval() (time.Duration, error) {
  1643. // return if we've already pulled it out
  1644. if s.groupByInterval != 0 {
  1645. return s.groupByInterval, nil
  1646. }
  1647. // Ignore if there are no dimensions.
  1648. if len(s.Dimensions) == 0 {
  1649. return 0, nil
  1650. }
  1651. for _, d := range s.Dimensions {
  1652. if call, ok := d.Expr.(*Call); ok && call.Name == "time" {
  1653. // Make sure there is exactly one argument.
  1654. if got := len(call.Args); got < 1 || got > 2 {
  1655. return 0, errors.New("time dimension expected 1 or 2 arguments")
  1656. }
  1657. // Ensure the argument is a duration.
  1658. lit, ok := call.Args[0].(*DurationLiteral)
  1659. if !ok {
  1660. return 0, errors.New("time dimension must have duration argument")
  1661. }
  1662. s.groupByInterval = lit.Val
  1663. return lit.Val, nil
  1664. }
  1665. }
  1666. return 0, nil
  1667. }
  1668. // GroupByOffset extracts the time interval offset, if specified.
  1669. func (s *SelectStatement) GroupByOffset() (time.Duration, error) {
  1670. interval, err := s.GroupByInterval()
  1671. if err != nil {
  1672. return 0, err
  1673. }
  1674. // Ignore if there are no dimensions.
  1675. if len(s.Dimensions) == 0 {
  1676. return 0, nil
  1677. }
  1678. for _, d := range s.Dimensions {
  1679. if call, ok := d.Expr.(*Call); ok && call.Name == "time" {
  1680. if len(call.Args) == 2 {
  1681. switch expr := call.Args[1].(type) {
  1682. case *DurationLiteral:
  1683. return expr.Val % interval, nil
  1684. case *TimeLiteral:
  1685. return expr.Val.Sub(expr.Val.Truncate(interval)), nil
  1686. default:
  1687. return 0, fmt.Errorf("invalid time dimension offset: %s", expr)
  1688. }
  1689. }
  1690. return 0, nil
  1691. }
  1692. }
  1693. return 0, nil
  1694. }
  1695. // SetTimeRange sets the start and end time of the select statement to [start, end). i.e. start inclusive, end exclusive.
  1696. // This is used commonly for continuous queries so the start and end are in buckets.
  1697. func (s *SelectStatement) SetTimeRange(start, end time.Time) error {
  1698. cond := fmt.Sprintf("time >= '%s' AND time < '%s'", start.UTC().Format(time.RFC3339Nano), end.UTC().Format(time.RFC3339Nano))
  1699. if s.Condition != nil {
  1700. cond = fmt.Sprintf("%s AND %s", s.rewriteWithoutTimeDimensions(), cond)
  1701. }
  1702. expr, err := NewParser(strings.NewReader(cond)).ParseExpr()
  1703. if err != nil {
  1704. return err
  1705. }
  1706. // Fold out any previously replaced time dimensions and set the condition.
  1707. s.Condition = Reduce(expr, nil)
  1708. return nil
  1709. }
  1710. // rewriteWithoutTimeDimensions will remove any WHERE time... clauses from the select statement.
  1711. // This is necessary when setting an explicit time range to override any that previously existed.
  1712. func (s *SelectStatement) rewriteWithoutTimeDimensions() string {
  1713. n := RewriteFunc(s.Condition, func(n Node) Node {
  1714. switch n := n.(type) {
  1715. case *BinaryExpr:
  1716. if n.LHS.String() == "time" {
  1717. return &BooleanLiteral{Val: true}
  1718. }
  1719. return n
  1720. case *Call:
  1721. return &BooleanLiteral{Val: true}
  1722. default:
  1723. return n
  1724. }
  1725. })
  1726. return n.String()
  1727. }
  1728. func encodeMeasurement(mm *Measurement) *internal.Measurement {
  1729. pb := &internal.Measurement{
  1730. Database: proto.String(mm.Database),
  1731. RetentionPolicy: proto.String(mm.RetentionPolicy),
  1732. Name: proto.String(mm.Name),
  1733. IsTarget: proto.Bool(mm.IsTarget),
  1734. }
  1735. if mm.Regex != nil {
  1736. pb.Regex = proto.String(mm.Regex.Val.String())
  1737. }
  1738. return pb
  1739. }
  1740. func decodeMeasurement(pb *internal.Measurement) (*Measurement, error) {
  1741. mm := &Measurement{
  1742. Database: pb.GetDatabase(),
  1743. RetentionPolicy: pb.GetRetentionPolicy(),
  1744. Name: pb.GetName(),
  1745. IsTarget: pb.GetIsTarget(),
  1746. }
  1747. if pb.Regex != nil {
  1748. regex, err := regexp.Compile(pb.GetRegex())
  1749. if err != nil {
  1750. return nil, fmt.Errorf("invalid binary measurement regex: value=%q, err=%s", pb.GetRegex(), err)
  1751. }
  1752. mm.Regex = &RegexLiteral{Val: regex}
  1753. }
  1754. return mm, nil
  1755. }
  1756. // walkNames will walk the Expr and return the identifier names used.
  1757. func walkNames(exp Expr) []string {
  1758. switch expr := exp.(type) {
  1759. case *VarRef:
  1760. return []string{expr.Val}
  1761. case *Call:
  1762. var a []string
  1763. for _, expr := range expr.Args {
  1764. if ref, ok := expr.(*VarRef); ok {
  1765. a = append(a, ref.Val)
  1766. }
  1767. }
  1768. return a
  1769. case *BinaryExpr:
  1770. var ret []string
  1771. ret = append(ret, walkNames(expr.LHS)...)
  1772. ret = append(ret, walkNames(expr.RHS)...)
  1773. return ret
  1774. case *ParenExpr:
  1775. return walkNames(expr.Expr)
  1776. }
  1777. return nil
  1778. }
  1779. // walkRefs will walk the Expr and return the var refs used.
  1780. func walkRefs(exp Expr) []VarRef {
  1781. refs := make(map[VarRef]struct{})
  1782. var walk func(exp Expr)
  1783. walk = func(exp Expr) {
  1784. switch expr := exp.(type) {
  1785. case *VarRef:
  1786. refs[*expr] = struct{}{}
  1787. case *Call:
  1788. for _, expr := range expr.Args {
  1789. if ref, ok := expr.(*VarRef); ok {
  1790. refs[*ref] = struct{}{}
  1791. }
  1792. }
  1793. case *BinaryExpr:
  1794. walk(expr.LHS)
  1795. walk(expr.RHS)
  1796. case *ParenExpr:
  1797. walk(expr.Expr)
  1798. }
  1799. }
  1800. walk(exp)
  1801. // Turn the map into a slice.
  1802. a := make([]VarRef, 0, len(refs))
  1803. for ref := range refs {
  1804. a = append(a, ref)
  1805. }
  1806. return a
  1807. }
  1808. // ExprNames returns a list of non-"time" field names from an expression.
  1809. func ExprNames(expr Expr) []VarRef {
  1810. m := make(map[VarRef]struct{})
  1811. for _, ref := range walkRefs(expr) {
  1812. if ref.Val == "time" {
  1813. continue
  1814. }
  1815. m[ref] = struct{}{}
  1816. }
  1817. a := make([]VarRef, 0, len(m))
  1818. for k := range m {
  1819. a = append(a, k)
  1820. }
  1821. sort.Sort(VarRefs(a))
  1822. return a
  1823. }
  1824. // Target represents a target (destination) policy, measurement, and DB.
  1825. type Target struct {
  1826. // Measurement to write into.
  1827. Measurement *Measurement
  1828. }
  1829. // String returns a string representation of the Target.
  1830. func (t *Target) String() string {
  1831. if t == nil {
  1832. return ""
  1833. }
  1834. var buf bytes.Buffer
  1835. _, _ = buf.WriteString("INTO ")
  1836. _, _ = buf.WriteString(t.Measurement.String())
  1837. if t.Measurement.Name == "" {
  1838. _, _ = buf.WriteString(":MEASUREMENT")
  1839. }
  1840. return buf.String()
  1841. }
  1842. // ExplainStatement represents a command for explaining a select statement.
  1843. type ExplainStatement struct {
  1844. Statement *SelectStatement
  1845. Analyze bool
  1846. }
  1847. // String returns a string representation of the explain statement.
  1848. func (e *ExplainStatement) String() string {
  1849. var buf bytes.Buffer
  1850. buf.WriteString("EXPLAIN ")
  1851. if e.Analyze {
  1852. buf.WriteString("ANALYZE ")
  1853. }
  1854. buf.WriteString(e.Statement.String())
  1855. return buf.String()
  1856. }
  1857. // RequiredPrivileges returns the privilege required to execute a ExplainStatement.
  1858. func (e *ExplainStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  1859. return e.Statement.RequiredPrivileges()
  1860. }
  1861. // DeleteStatement represents a command for deleting data from the database.
  1862. type DeleteStatement struct {
  1863. // Data source that values are removed from.
  1864. Source Source
  1865. // An expression evaluated on data point.
  1866. Condition Expr
  1867. }
  1868. // String returns a string representation of the delete statement.
  1869. func (s *DeleteStatement) String() string {
  1870. var buf bytes.Buffer
  1871. _, _ = buf.WriteString("DELETE FROM ")
  1872. _, _ = buf.WriteString(s.Source.String())
  1873. if s.Condition != nil {
  1874. _, _ = buf.WriteString(" WHERE ")
  1875. _, _ = buf.WriteString(s.Condition.String())
  1876. }
  1877. return buf.String()
  1878. }
  1879. // RequiredPrivileges returns the privilege required to execute a DeleteStatement.
  1880. func (s *DeleteStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  1881. return ExecutionPrivileges{{Admin: false, Name: "", Privilege: WritePrivilege}}, nil
  1882. }
  1883. // DefaultDatabase returns the default database from the statement.
  1884. func (s *DeleteStatement) DefaultDatabase() string {
  1885. if m, ok := s.Source.(*Measurement); ok {
  1886. return m.Database
  1887. }
  1888. return ""
  1889. }
  1890. // ShowSeriesStatement represents a command for listing series in the database.
  1891. type ShowSeriesStatement struct {
  1892. // Database to query. If blank, use the default database.
  1893. // The database can also be specified per source in the Sources.
  1894. Database string
  1895. // Measurement(s) the series are listed for.
  1896. Sources Sources
  1897. // An expression evaluated on a series name or tag.
  1898. Condition Expr
  1899. // Fields to sort results by
  1900. SortFields SortFields
  1901. // Maximum number of rows to be returned.
  1902. // Unlimited if zero.
  1903. Limit int
  1904. // Returns rows starting at an offset from the first row.
  1905. Offset int
  1906. }
  1907. // String returns a string representation of the list series statement.
  1908. func (s *ShowSeriesStatement) String() string {
  1909. var buf bytes.Buffer
  1910. _, _ = buf.WriteString("SHOW SERIES")
  1911. if s.Database != "" {
  1912. _, _ = buf.WriteString(" ON ")
  1913. _, _ = buf.WriteString(QuoteIdent(s.Database))
  1914. }
  1915. if s.Sources != nil {
  1916. _, _ = buf.WriteString(" FROM ")
  1917. _, _ = buf.WriteString(s.Sources.String())
  1918. }
  1919. if s.Condition != nil {
  1920. _, _ = buf.WriteString(" WHERE ")
  1921. _, _ = buf.WriteString(s.Condition.String())
  1922. }
  1923. if len(s.SortFields) > 0 {
  1924. _, _ = buf.WriteString(" ORDER BY ")
  1925. _, _ = buf.WriteString(s.SortFields.String())
  1926. }
  1927. if s.Limit > 0 {
  1928. _, _ = buf.WriteString(" LIMIT ")
  1929. _, _ = buf.WriteString(strconv.Itoa(s.Limit))
  1930. }
  1931. if s.Offset > 0 {
  1932. _, _ = buf.WriteString(" OFFSET ")
  1933. _, _ = buf.WriteString(strconv.Itoa(s.Offset))
  1934. }
  1935. return buf.String()
  1936. }
  1937. // RequiredPrivileges returns the privilege required to execute a ShowSeriesStatement.
  1938. func (s *ShowSeriesStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  1939. return ExecutionPrivileges{{Admin: false, Name: s.Database, Privilege: ReadPrivilege}}, nil
  1940. }
  1941. // DefaultDatabase returns the default database from the statement.
  1942. func (s *ShowSeriesStatement) DefaultDatabase() string {
  1943. return s.Database
  1944. }
  1945. // DropSeriesStatement represents a command for removing a series from the database.
  1946. type DropSeriesStatement struct {
  1947. // Data source that fields are extracted from (optional)
  1948. Sources Sources
  1949. // An expression evaluated on data point (optional)
  1950. Condition Expr
  1951. }
  1952. // String returns a string representation of the drop series statement.
  1953. func (s *DropSeriesStatement) String() string {
  1954. var buf bytes.Buffer
  1955. buf.WriteString("DROP SERIES")
  1956. if s.Sources != nil {
  1957. buf.WriteString(" FROM ")
  1958. buf.WriteString(s.Sources.String())
  1959. }
  1960. if s.Condition != nil {
  1961. buf.WriteString(" WHERE ")
  1962. buf.WriteString(s.Condition.String())
  1963. }
  1964. return buf.String()
  1965. }
  1966. // RequiredPrivileges returns the privilege required to execute a DropSeriesStatement.
  1967. func (s DropSeriesStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  1968. return ExecutionPrivileges{{Admin: false, Name: "", Privilege: WritePrivilege}}, nil
  1969. }
  1970. // DeleteSeriesStatement represents a command for deleting all or part of a series from a database.
  1971. type DeleteSeriesStatement struct {
  1972. // Data source that fields are extracted from (optional)
  1973. Sources Sources
  1974. // An expression evaluated on data point (optional)
  1975. Condition Expr
  1976. }
  1977. // String returns a string representation of the delete series statement.
  1978. func (s *DeleteSeriesStatement) String() string {
  1979. var buf bytes.Buffer
  1980. buf.WriteString("DELETE")
  1981. if s.Sources != nil {
  1982. buf.WriteString(" FROM ")
  1983. buf.WriteString(s.Sources.String())
  1984. }
  1985. if s.Condition != nil {
  1986. buf.WriteString(" WHERE ")
  1987. buf.WriteString(s.Condition.String())
  1988. }
  1989. return buf.String()
  1990. }
  1991. // RequiredPrivileges returns the privilege required to execute a DeleteSeriesStatement.
  1992. func (s DeleteSeriesStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  1993. return ExecutionPrivileges{{Admin: false, Name: "", Privilege: WritePrivilege}}, nil
  1994. }
  1995. // DropShardStatement represents a command for removing a shard from
  1996. // the node.
  1997. type DropShardStatement struct {
  1998. // ID of the shard to be dropped.
  1999. ID uint64
  2000. }
  2001. // String returns a string representation of the drop series statement.
  2002. func (s *DropShardStatement) String() string {
  2003. var buf bytes.Buffer
  2004. buf.WriteString("DROP SHARD ")
  2005. buf.WriteString(strconv.FormatUint(s.ID, 10))
  2006. return buf.String()
  2007. }
  2008. // RequiredPrivileges returns the privilege required to execute a
  2009. // DropShardStatement.
  2010. func (s *DropShardStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  2011. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}, nil
  2012. }
  2013. // ShowSeriesCardinalityStatement represents a command for listing series cardinality.
  2014. type ShowSeriesCardinalityStatement struct {
  2015. // Database to query. If blank, use the default database.
  2016. // The database can also be specified per source in the Sources.
  2017. Database string
  2018. // Specifies whether the user requires exact counting or not.
  2019. Exact bool
  2020. // Measurement(s) the series are listed for.
  2021. Sources Sources
  2022. // An expression evaluated on a series name or tag.
  2023. Condition Expr
  2024. // Expressions used for grouping the selection.
  2025. Dimensions Dimensions
  2026. Limit, Offset int
  2027. }
  2028. // String returns a string representation of the show continuous queries statement.
  2029. func (s *ShowSeriesCardinalityStatement) String() string {
  2030. var buf bytes.Buffer
  2031. _, _ = buf.WriteString("SHOW SERIES")
  2032. if s.Exact {
  2033. _, _ = buf.WriteString(" EXACT")
  2034. }
  2035. _, _ = buf.WriteString(" CARDINALITY")
  2036. if s.Database != "" {
  2037. _, _ = buf.WriteString(" ON ")
  2038. _, _ = buf.WriteString(QuoteIdent(s.Database))
  2039. }
  2040. if s.Sources != nil {
  2041. _, _ = buf.WriteString(" FROM ")
  2042. _, _ = buf.WriteString(s.Sources.String())
  2043. }
  2044. if s.Condition != nil {
  2045. _, _ = buf.WriteString(" WHERE ")
  2046. _, _ = buf.WriteString(s.Condition.String())
  2047. }
  2048. if len(s.Dimensions) > 0 {
  2049. _, _ = buf.WriteString(" GROUP BY ")
  2050. _, _ = buf.WriteString(s.Dimensions.String())
  2051. }
  2052. if s.Limit > 0 {
  2053. _, _ = fmt.Fprintf(&buf, " LIMIT %d", s.Limit)
  2054. }
  2055. if s.Offset > 0 {
  2056. _, _ = buf.WriteString(" OFFSET ")
  2057. _, _ = buf.WriteString(strconv.Itoa(s.Offset))
  2058. }
  2059. return buf.String()
  2060. }
  2061. // RequiredPrivileges returns the privilege required to execute a ShowSeriesCardinalityStatement.
  2062. func (s *ShowSeriesCardinalityStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  2063. if !s.Exact {
  2064. return ExecutionPrivileges{{Admin: false, Name: s.Database, Privilege: ReadPrivilege}}, nil
  2065. }
  2066. return s.Sources.RequiredPrivileges()
  2067. }
  2068. // DefaultDatabase returns the default database from the statement.
  2069. func (s *ShowSeriesCardinalityStatement) DefaultDatabase() string {
  2070. return s.Database
  2071. }
  2072. // ShowContinuousQueriesStatement represents a command for listing continuous queries.
  2073. type ShowContinuousQueriesStatement struct{}
  2074. // String returns a string representation of the show continuous queries statement.
  2075. func (s *ShowContinuousQueriesStatement) String() string { return "SHOW CONTINUOUS QUERIES" }
  2076. // RequiredPrivileges returns the privilege required to execute a ShowContinuousQueriesStatement.
  2077. func (s *ShowContinuousQueriesStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  2078. return ExecutionPrivileges{{Admin: false, Name: "", Privilege: ReadPrivilege}}, nil
  2079. }
  2080. // ShowGrantsForUserStatement represents a command for listing user privileges.
  2081. type ShowGrantsForUserStatement struct {
  2082. // Name of the user to display privileges.
  2083. Name string
  2084. }
  2085. // String returns a string representation of the show grants for user.
  2086. func (s *ShowGrantsForUserStatement) String() string {
  2087. var buf bytes.Buffer
  2088. _, _ = buf.WriteString("SHOW GRANTS FOR ")
  2089. _, _ = buf.WriteString(QuoteIdent(s.Name))
  2090. return buf.String()
  2091. }
  2092. // RequiredPrivileges returns the privilege required to execute a ShowGrantsForUserStatement
  2093. func (s *ShowGrantsForUserStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  2094. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}, nil
  2095. }
  2096. // ShowDatabasesStatement represents a command for listing all databases in the cluster.
  2097. type ShowDatabasesStatement struct{}
  2098. // String returns a string representation of the show databases command.
  2099. func (s *ShowDatabasesStatement) String() string { return "SHOW DATABASES" }
  2100. // RequiredPrivileges returns the privilege required to execute a ShowDatabasesStatement.
  2101. func (s *ShowDatabasesStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  2102. // SHOW DATABASES is one of few statements that have no required privileges.
  2103. // Anyone is allowed to execute it, but the returned results depend on the user's
  2104. // individual database permissions.
  2105. return ExecutionPrivileges{{Admin: false, Name: "", Privilege: NoPrivileges}}, nil
  2106. }
  2107. // CreateContinuousQueryStatement represents a command for creating a continuous query.
  2108. type CreateContinuousQueryStatement struct {
  2109. // Name of the continuous query to be created.
  2110. Name string
  2111. // Name of the database to create the continuous query on.
  2112. Database string
  2113. // Source of data (SELECT statement).
  2114. Source *SelectStatement
  2115. // Interval to resample previous queries.
  2116. ResampleEvery time.Duration
  2117. // Maximum duration to resample previous queries.
  2118. ResampleFor time.Duration
  2119. }
  2120. // String returns a string representation of the statement.
  2121. func (s *CreateContinuousQueryStatement) String() string {
  2122. var buf bytes.Buffer
  2123. fmt.Fprintf(&buf, "CREATE CONTINUOUS QUERY %s ON %s ", QuoteIdent(s.Name), QuoteIdent(s.Database))
  2124. if s.ResampleEvery > 0 || s.ResampleFor > 0 {
  2125. buf.WriteString("RESAMPLE ")
  2126. if s.ResampleEvery > 0 {
  2127. fmt.Fprintf(&buf, "EVERY %s ", FormatDuration(s.ResampleEvery))
  2128. }
  2129. if s.ResampleFor > 0 {
  2130. fmt.Fprintf(&buf, "FOR %s ", FormatDuration(s.ResampleFor))
  2131. }
  2132. }
  2133. fmt.Fprintf(&buf, "BEGIN %s END", s.Source.String())
  2134. return buf.String()
  2135. }
  2136. // DefaultDatabase returns the default database from the statement.
  2137. func (s *CreateContinuousQueryStatement) DefaultDatabase() string {
  2138. return s.Database
  2139. }
  2140. // RequiredPrivileges returns the privilege required to execute a CreateContinuousQueryStatement.
  2141. func (s *CreateContinuousQueryStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  2142. ep := ExecutionPrivileges{{Admin: false, Name: s.Database, Privilege: ReadPrivilege}}
  2143. // Selecting into a database that's different from the source?
  2144. if s.Source.Target.Measurement.Database != "" {
  2145. // Change source database privilege requirement to read.
  2146. ep[0].Privilege = ReadPrivilege
  2147. // Add destination database privilege requirement and set it to write.
  2148. p := ExecutionPrivilege{
  2149. Admin: false,
  2150. Name: s.Source.Target.Measurement.Database,
  2151. Privilege: WritePrivilege,
  2152. }
  2153. ep = append(ep, p)
  2154. }
  2155. return ep, nil
  2156. }
  2157. func (s *CreateContinuousQueryStatement) validate() error {
  2158. interval, err := s.Source.GroupByInterval()
  2159. if err != nil {
  2160. return err
  2161. }
  2162. if s.ResampleFor != 0 {
  2163. if s.ResampleEvery != 0 && s.ResampleEvery > interval {
  2164. interval = s.ResampleEvery
  2165. }
  2166. if interval > s.ResampleFor {
  2167. return fmt.Errorf("FOR duration must be >= GROUP BY time duration: must be a minimum of %s, got %s", FormatDuration(interval), FormatDuration(s.ResampleFor))
  2168. }
  2169. }
  2170. return nil
  2171. }
  2172. // DropContinuousQueryStatement represents a command for removing a continuous query.
  2173. type DropContinuousQueryStatement struct {
  2174. Name string
  2175. Database string
  2176. }
  2177. // String returns a string representation of the statement.
  2178. func (s *DropContinuousQueryStatement) String() string {
  2179. return fmt.Sprintf("DROP CONTINUOUS QUERY %s ON %s", QuoteIdent(s.Name), QuoteIdent(s.Database))
  2180. }
  2181. // RequiredPrivileges returns the privilege(s) required to execute a DropContinuousQueryStatement
  2182. func (s *DropContinuousQueryStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  2183. return ExecutionPrivileges{{Admin: false, Name: s.Database, Privilege: WritePrivilege}}, nil
  2184. }
  2185. // DefaultDatabase returns the default database from the statement.
  2186. func (s *DropContinuousQueryStatement) DefaultDatabase() string {
  2187. return s.Database
  2188. }
  2189. // ShowMeasurementCardinalityStatement represents a command for listing measurement cardinality.
  2190. type ShowMeasurementCardinalityStatement struct {
  2191. Exact bool // If false then cardinality estimation will be used.
  2192. Database string
  2193. Sources Sources
  2194. Condition Expr
  2195. Dimensions Dimensions
  2196. Limit, Offset int
  2197. }
  2198. // String returns a string representation of the statement.
  2199. func (s *ShowMeasurementCardinalityStatement) String() string {
  2200. var buf bytes.Buffer
  2201. _, _ = buf.WriteString("SHOW MEASUREMENT")
  2202. if s.Exact {
  2203. _, _ = buf.WriteString(" EXACT")
  2204. }
  2205. _, _ = buf.WriteString(" CARDINALITY")
  2206. if s.Database != "" {
  2207. _, _ = buf.WriteString(" ON ")
  2208. _, _ = buf.WriteString(QuoteIdent(s.Database))
  2209. }
  2210. if s.Sources != nil {
  2211. _, _ = buf.WriteString(" FROM ")
  2212. _, _ = buf.WriteString(s.Sources.String())
  2213. }
  2214. if s.Condition != nil {
  2215. _, _ = buf.WriteString(" WHERE ")
  2216. _, _ = buf.WriteString(s.Condition.String())
  2217. }
  2218. if len(s.Dimensions) > 0 {
  2219. _, _ = buf.WriteString(" GROUP BY ")
  2220. _, _ = buf.WriteString(s.Dimensions.String())
  2221. }
  2222. if s.Limit > 0 {
  2223. _, _ = fmt.Fprintf(&buf, " LIMIT %d", s.Limit)
  2224. }
  2225. if s.Offset > 0 {
  2226. _, _ = buf.WriteString(" OFFSET ")
  2227. _, _ = buf.WriteString(strconv.Itoa(s.Offset))
  2228. }
  2229. return buf.String()
  2230. }
  2231. // RequiredPrivileges returns the privilege required to execute a ShowMeasurementCardinalityStatement.
  2232. func (s *ShowMeasurementCardinalityStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  2233. if !s.Exact {
  2234. return ExecutionPrivileges{{Admin: false, Name: s.Database, Privilege: ReadPrivilege}}, nil
  2235. }
  2236. return s.Sources.RequiredPrivileges()
  2237. }
  2238. // DefaultDatabase returns the default database from the statement.
  2239. func (s *ShowMeasurementCardinalityStatement) DefaultDatabase() string {
  2240. return s.Database
  2241. }
  2242. // ShowMeasurementsStatement represents a command for listing measurements.
  2243. type ShowMeasurementsStatement struct {
  2244. // Database to query. If blank, use the default database.
  2245. Database string
  2246. // Measurement name or regex.
  2247. Source Source
  2248. // An expression evaluated on data point.
  2249. Condition Expr
  2250. // Fields to sort results by
  2251. SortFields SortFields
  2252. // Maximum number of rows to be returned.
  2253. // Unlimited if zero.
  2254. Limit int
  2255. // Returns rows starting at an offset from the first row.
  2256. Offset int
  2257. }
  2258. // String returns a string representation of the statement.
  2259. func (s *ShowMeasurementsStatement) String() string {
  2260. var buf bytes.Buffer
  2261. _, _ = buf.WriteString("SHOW MEASUREMENTS")
  2262. if s.Database != "" {
  2263. _, _ = buf.WriteString(" ON ")
  2264. _, _ = buf.WriteString(s.Database)
  2265. }
  2266. if s.Source != nil {
  2267. _, _ = buf.WriteString(" WITH MEASUREMENT ")
  2268. if m, ok := s.Source.(*Measurement); ok && m.Regex != nil {
  2269. _, _ = buf.WriteString("=~ ")
  2270. } else {
  2271. _, _ = buf.WriteString("= ")
  2272. }
  2273. _, _ = buf.WriteString(s.Source.String())
  2274. }
  2275. if s.Condition != nil {
  2276. _, _ = buf.WriteString(" WHERE ")
  2277. _, _ = buf.WriteString(s.Condition.String())
  2278. }
  2279. if len(s.SortFields) > 0 {
  2280. _, _ = buf.WriteString(" ORDER BY ")
  2281. _, _ = buf.WriteString(s.SortFields.String())
  2282. }
  2283. if s.Limit > 0 {
  2284. _, _ = buf.WriteString(" LIMIT ")
  2285. _, _ = buf.WriteString(strconv.Itoa(s.Limit))
  2286. }
  2287. if s.Offset > 0 {
  2288. _, _ = buf.WriteString(" OFFSET ")
  2289. _, _ = buf.WriteString(strconv.Itoa(s.Offset))
  2290. }
  2291. return buf.String()
  2292. }
  2293. // RequiredPrivileges returns the privilege(s) required to execute a ShowMeasurementsStatement.
  2294. func (s *ShowMeasurementsStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  2295. return ExecutionPrivileges{{Admin: false, Name: s.Database, Privilege: ReadPrivilege}}, nil
  2296. }
  2297. // DefaultDatabase returns the default database from the statement.
  2298. func (s *ShowMeasurementsStatement) DefaultDatabase() string {
  2299. return s.Database
  2300. }
  2301. // DropMeasurementStatement represents a command to drop a measurement.
  2302. type DropMeasurementStatement struct {
  2303. // Name of the measurement to be dropped.
  2304. Name string
  2305. }
  2306. // String returns a string representation of the drop measurement statement.
  2307. func (s *DropMeasurementStatement) String() string {
  2308. var buf bytes.Buffer
  2309. _, _ = buf.WriteString("DROP MEASUREMENT ")
  2310. _, _ = buf.WriteString(QuoteIdent(s.Name))
  2311. return buf.String()
  2312. }
  2313. // RequiredPrivileges returns the privilege(s) required to execute a DropMeasurementStatement
  2314. func (s *DropMeasurementStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  2315. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}, nil
  2316. }
  2317. // ShowQueriesStatement represents a command for listing all running queries.
  2318. type ShowQueriesStatement struct{}
  2319. // String returns a string representation of the show queries statement.
  2320. func (s *ShowQueriesStatement) String() string {
  2321. return "SHOW QUERIES"
  2322. }
  2323. // RequiredPrivileges returns the privilege required to execute a ShowQueriesStatement.
  2324. func (s *ShowQueriesStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  2325. return ExecutionPrivileges{{Admin: false, Name: "", Privilege: ReadPrivilege}}, nil
  2326. }
  2327. // ShowRetentionPoliciesStatement represents a command for listing retention policies.
  2328. type ShowRetentionPoliciesStatement struct {
  2329. // Name of the database to list policies for.
  2330. Database string
  2331. }
  2332. // String returns a string representation of a ShowRetentionPoliciesStatement.
  2333. func (s *ShowRetentionPoliciesStatement) String() string {
  2334. var buf bytes.Buffer
  2335. _, _ = buf.WriteString("SHOW RETENTION POLICIES")
  2336. if s.Database != "" {
  2337. _, _ = buf.WriteString(" ON ")
  2338. _, _ = buf.WriteString(QuoteIdent(s.Database))
  2339. }
  2340. return buf.String()
  2341. }
  2342. // RequiredPrivileges returns the privilege(s) required to execute a ShowRetentionPoliciesStatement
  2343. func (s *ShowRetentionPoliciesStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  2344. return ExecutionPrivileges{{Admin: false, Name: s.Database, Privilege: ReadPrivilege}}, nil
  2345. }
  2346. // DefaultDatabase returns the default database from the statement.
  2347. func (s *ShowRetentionPoliciesStatement) DefaultDatabase() string {
  2348. return s.Database
  2349. }
  2350. // ShowStatsStatement displays statistics for a given module.
  2351. type ShowStatsStatement struct {
  2352. Module string
  2353. }
  2354. // String returns a string representation of a ShowStatsStatement.
  2355. func (s *ShowStatsStatement) String() string {
  2356. var buf bytes.Buffer
  2357. _, _ = buf.WriteString("SHOW STATS")
  2358. if s.Module != "" {
  2359. _, _ = buf.WriteString(" FOR ")
  2360. _, _ = buf.WriteString(QuoteString(s.Module))
  2361. }
  2362. return buf.String()
  2363. }
  2364. // RequiredPrivileges returns the privilege(s) required to execute a ShowStatsStatement
  2365. func (s *ShowStatsStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  2366. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}, nil
  2367. }
  2368. // ShowShardGroupsStatement represents a command for displaying shard groups in the cluster.
  2369. type ShowShardGroupsStatement struct{}
  2370. // String returns a string representation of the SHOW SHARD GROUPS command.
  2371. func (s *ShowShardGroupsStatement) String() string { return "SHOW SHARD GROUPS" }
  2372. // RequiredPrivileges returns the privileges required to execute the statement.
  2373. func (s *ShowShardGroupsStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  2374. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}, nil
  2375. }
  2376. // ShowShardsStatement represents a command for displaying shards in the cluster.
  2377. type ShowShardsStatement struct{}
  2378. // String returns a string representation.
  2379. func (s *ShowShardsStatement) String() string { return "SHOW SHARDS" }
  2380. // RequiredPrivileges returns the privileges required to execute the statement.
  2381. func (s *ShowShardsStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  2382. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}, nil
  2383. }
  2384. // ShowDiagnosticsStatement represents a command for show node diagnostics.
  2385. type ShowDiagnosticsStatement struct {
  2386. // Module
  2387. Module string
  2388. }
  2389. // String returns a string representation of the ShowDiagnosticsStatement.
  2390. func (s *ShowDiagnosticsStatement) String() string {
  2391. var buf bytes.Buffer
  2392. _, _ = buf.WriteString("SHOW DIAGNOSTICS")
  2393. if s.Module != "" {
  2394. _, _ = buf.WriteString(" FOR ")
  2395. _, _ = buf.WriteString(QuoteString(s.Module))
  2396. }
  2397. return buf.String()
  2398. }
  2399. // RequiredPrivileges returns the privilege required to execute a ShowDiagnosticsStatement
  2400. func (s *ShowDiagnosticsStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  2401. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}, nil
  2402. }
  2403. // CreateSubscriptionStatement represents a command to add a subscription to the incoming data stream.
  2404. type CreateSubscriptionStatement struct {
  2405. Name string
  2406. Database string
  2407. RetentionPolicy string
  2408. Destinations []string
  2409. Mode string
  2410. }
  2411. // String returns a string representation of the CreateSubscriptionStatement.
  2412. func (s *CreateSubscriptionStatement) String() string {
  2413. var buf bytes.Buffer
  2414. _, _ = buf.WriteString("CREATE SUBSCRIPTION ")
  2415. _, _ = buf.WriteString(QuoteIdent(s.Name))
  2416. _, _ = buf.WriteString(" ON ")
  2417. _, _ = buf.WriteString(QuoteIdent(s.Database))
  2418. _, _ = buf.WriteString(".")
  2419. _, _ = buf.WriteString(QuoteIdent(s.RetentionPolicy))
  2420. _, _ = buf.WriteString(" DESTINATIONS ")
  2421. _, _ = buf.WriteString(s.Mode)
  2422. _, _ = buf.WriteString(" ")
  2423. for i, dest := range s.Destinations {
  2424. if i != 0 {
  2425. _, _ = buf.WriteString(", ")
  2426. }
  2427. _, _ = buf.WriteString(QuoteString(dest))
  2428. }
  2429. return buf.String()
  2430. }
  2431. // RequiredPrivileges returns the privilege required to execute a CreateSubscriptionStatement.
  2432. func (s *CreateSubscriptionStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  2433. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}, nil
  2434. }
  2435. // DefaultDatabase returns the default database from the statement.
  2436. func (s *CreateSubscriptionStatement) DefaultDatabase() string {
  2437. return s.Database
  2438. }
  2439. // DropSubscriptionStatement represents a command to drop a subscription to the incoming data stream.
  2440. type DropSubscriptionStatement struct {
  2441. Name string
  2442. Database string
  2443. RetentionPolicy string
  2444. }
  2445. // String returns a string representation of the DropSubscriptionStatement.
  2446. func (s *DropSubscriptionStatement) String() string {
  2447. return fmt.Sprintf(`DROP SUBSCRIPTION %s ON %s.%s`, QuoteIdent(s.Name), QuoteIdent(s.Database), QuoteIdent(s.RetentionPolicy))
  2448. }
  2449. // RequiredPrivileges returns the privilege required to execute a DropSubscriptionStatement
  2450. func (s *DropSubscriptionStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  2451. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}, nil
  2452. }
  2453. // DefaultDatabase returns the default database from the statement.
  2454. func (s *DropSubscriptionStatement) DefaultDatabase() string {
  2455. return s.Database
  2456. }
  2457. // ShowSubscriptionsStatement represents a command to show a list of subscriptions.
  2458. type ShowSubscriptionsStatement struct {
  2459. }
  2460. // String returns a string representation of the ShowSubscriptionsStatement.
  2461. func (s *ShowSubscriptionsStatement) String() string {
  2462. return "SHOW SUBSCRIPTIONS"
  2463. }
  2464. // RequiredPrivileges returns the privilege required to execute a ShowSubscriptionsStatement.
  2465. func (s *ShowSubscriptionsStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  2466. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}, nil
  2467. }
  2468. // ShowTagKeysStatement represents a command for listing tag keys.
  2469. type ShowTagKeysStatement struct {
  2470. // Database to query. If blank, use the default database.
  2471. // The database can also be specified per source in the Sources.
  2472. Database string
  2473. // Data sources that fields are extracted from.
  2474. Sources Sources
  2475. // An expression evaluated on data point.
  2476. Condition Expr
  2477. // Fields to sort results by.
  2478. SortFields SortFields
  2479. // Maximum number of tag keys per measurement. Unlimited if zero.
  2480. Limit int
  2481. // Returns tag keys starting at an offset from the first row.
  2482. Offset int
  2483. // Maxiumum number of series to be returned. Unlimited if zero.
  2484. SLimit int
  2485. // Returns series starting at an offset from the first one.
  2486. SOffset int
  2487. }
  2488. // String returns a string representation of the statement.
  2489. func (s *ShowTagKeysStatement) String() string {
  2490. var buf bytes.Buffer
  2491. _, _ = buf.WriteString("SHOW TAG KEYS")
  2492. if s.Database != "" {
  2493. _, _ = buf.WriteString(" ON ")
  2494. _, _ = buf.WriteString(QuoteIdent(s.Database))
  2495. }
  2496. if s.Sources != nil {
  2497. _, _ = buf.WriteString(" FROM ")
  2498. _, _ = buf.WriteString(s.Sources.String())
  2499. }
  2500. if s.Condition != nil {
  2501. _, _ = buf.WriteString(" WHERE ")
  2502. _, _ = buf.WriteString(s.Condition.String())
  2503. }
  2504. if len(s.SortFields) > 0 {
  2505. _, _ = buf.WriteString(" ORDER BY ")
  2506. _, _ = buf.WriteString(s.SortFields.String())
  2507. }
  2508. if s.Limit > 0 {
  2509. _, _ = buf.WriteString(" LIMIT ")
  2510. _, _ = buf.WriteString(strconv.Itoa(s.Limit))
  2511. }
  2512. if s.Offset > 0 {
  2513. _, _ = buf.WriteString(" OFFSET ")
  2514. _, _ = buf.WriteString(strconv.Itoa(s.Offset))
  2515. }
  2516. if s.SLimit > 0 {
  2517. _, _ = buf.WriteString(" SLIMIT ")
  2518. _, _ = buf.WriteString(strconv.Itoa(s.SLimit))
  2519. }
  2520. if s.SOffset > 0 {
  2521. _, _ = buf.WriteString(" SOFFSET ")
  2522. _, _ = buf.WriteString(strconv.Itoa(s.SOffset))
  2523. }
  2524. return buf.String()
  2525. }
  2526. // RequiredPrivileges returns the privilege(s) required to execute a ShowTagKeysStatement.
  2527. func (s *ShowTagKeysStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  2528. return ExecutionPrivileges{{Admin: false, Name: s.Database, Privilege: ReadPrivilege}}, nil
  2529. }
  2530. // DefaultDatabase returns the default database from the statement.
  2531. func (s *ShowTagKeysStatement) DefaultDatabase() string {
  2532. return s.Database
  2533. }
  2534. // ShowTagKeyCardinalityStatement represents a command for listing tag key cardinality.
  2535. type ShowTagKeyCardinalityStatement struct {
  2536. Database string
  2537. Exact bool
  2538. Sources Sources
  2539. Condition Expr
  2540. Dimensions Dimensions
  2541. Limit, Offset int
  2542. }
  2543. // String returns a string representation of the statement.
  2544. func (s *ShowTagKeyCardinalityStatement) String() string {
  2545. var buf bytes.Buffer
  2546. _, _ = buf.WriteString("SHOW TAG KEY ")
  2547. if s.Exact {
  2548. _, _ = buf.WriteString("EXACT ")
  2549. }
  2550. _, _ = buf.WriteString("CARDINALITY")
  2551. if s.Database != "" {
  2552. _, _ = buf.WriteString(" ON ")
  2553. _, _ = buf.WriteString(QuoteIdent(s.Database))
  2554. }
  2555. if s.Sources != nil {
  2556. _, _ = buf.WriteString(" FROM ")
  2557. _, _ = buf.WriteString(s.Sources.String())
  2558. }
  2559. if s.Condition != nil {
  2560. _, _ = buf.WriteString(" WHERE ")
  2561. _, _ = buf.WriteString(s.Condition.String())
  2562. }
  2563. if len(s.Dimensions) > 0 {
  2564. _, _ = buf.WriteString(" GROUP BY ")
  2565. _, _ = buf.WriteString(s.Dimensions.String())
  2566. }
  2567. if s.Limit > 0 {
  2568. _, _ = fmt.Fprintf(&buf, " LIMIT %d", s.Limit)
  2569. }
  2570. if s.Offset > 0 {
  2571. _, _ = buf.WriteString(" OFFSET ")
  2572. _, _ = buf.WriteString(strconv.Itoa(s.Offset))
  2573. }
  2574. return buf.String()
  2575. }
  2576. // RequiredPrivileges returns the privilege required to execute a ShowTagKeyCardinalityStatement.
  2577. func (s *ShowTagKeyCardinalityStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  2578. return s.Sources.RequiredPrivileges()
  2579. }
  2580. // DefaultDatabase returns the default database from the statement.
  2581. func (s *ShowTagKeyCardinalityStatement) DefaultDatabase() string {
  2582. return s.Database
  2583. }
  2584. // ShowTagValuesStatement represents a command for listing tag values.
  2585. type ShowTagValuesStatement struct {
  2586. // Database to query. If blank, use the default database.
  2587. // The database can also be specified per source in the Sources.
  2588. Database string
  2589. // Data source that fields are extracted from.
  2590. Sources Sources
  2591. // Operation to use when selecting tag key(s).
  2592. Op Token
  2593. // Literal to compare the tag key(s) with.
  2594. TagKeyExpr Literal
  2595. // An expression evaluated on data point.
  2596. Condition Expr
  2597. // Fields to sort results by.
  2598. SortFields SortFields
  2599. // Maximum number of rows to be returned.
  2600. // Unlimited if zero.
  2601. Limit int
  2602. // Returns rows starting at an offset from the first row.
  2603. Offset int
  2604. }
  2605. // String returns a string representation of the statement.
  2606. func (s *ShowTagValuesStatement) String() string {
  2607. var buf bytes.Buffer
  2608. _, _ = buf.WriteString("SHOW TAG VALUES")
  2609. if s.Database != "" {
  2610. _, _ = buf.WriteString(" ON ")
  2611. _, _ = buf.WriteString(QuoteIdent(s.Database))
  2612. }
  2613. if s.Sources != nil {
  2614. _, _ = buf.WriteString(" FROM ")
  2615. _, _ = buf.WriteString(s.Sources.String())
  2616. }
  2617. _, _ = buf.WriteString(" WITH KEY ")
  2618. _, _ = buf.WriteString(s.Op.String())
  2619. _, _ = buf.WriteString(" ")
  2620. if lit, ok := s.TagKeyExpr.(*StringLiteral); ok {
  2621. _, _ = buf.WriteString(QuoteIdent(lit.Val))
  2622. } else {
  2623. _, _ = buf.WriteString(s.TagKeyExpr.String())
  2624. }
  2625. if s.Condition != nil {
  2626. _, _ = buf.WriteString(" WHERE ")
  2627. _, _ = buf.WriteString(s.Condition.String())
  2628. }
  2629. if len(s.SortFields) > 0 {
  2630. _, _ = buf.WriteString(" ORDER BY ")
  2631. _, _ = buf.WriteString(s.SortFields.String())
  2632. }
  2633. if s.Limit > 0 {
  2634. _, _ = buf.WriteString(" LIMIT ")
  2635. _, _ = buf.WriteString(strconv.Itoa(s.Limit))
  2636. }
  2637. if s.Offset > 0 {
  2638. _, _ = buf.WriteString(" OFFSET ")
  2639. _, _ = buf.WriteString(strconv.Itoa(s.Offset))
  2640. }
  2641. return buf.String()
  2642. }
  2643. // RequiredPrivileges returns the privilege(s) required to execute a ShowTagValuesStatement.
  2644. func (s *ShowTagValuesStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  2645. return ExecutionPrivileges{{Admin: false, Name: s.Database, Privilege: ReadPrivilege}}, nil
  2646. }
  2647. // DefaultDatabase returns the default database from the statement.
  2648. func (s *ShowTagValuesStatement) DefaultDatabase() string {
  2649. return s.Database
  2650. }
  2651. // ShowTagValuesCardinalityStatement represents a command for listing tag value cardinality.
  2652. type ShowTagValuesCardinalityStatement struct {
  2653. Database string
  2654. Exact bool
  2655. Sources Sources
  2656. Op Token
  2657. TagKeyExpr Literal
  2658. Condition Expr
  2659. Dimensions Dimensions
  2660. Limit, Offset int
  2661. }
  2662. // String returns a string representation of the statement.
  2663. func (s *ShowTagValuesCardinalityStatement) String() string {
  2664. var buf bytes.Buffer
  2665. _, _ = buf.WriteString("SHOW TAG VALUES ")
  2666. if s.Exact {
  2667. _, _ = buf.WriteString("EXACT ")
  2668. }
  2669. _, _ = buf.WriteString("CARDINALITY")
  2670. if s.Database != "" {
  2671. _, _ = buf.WriteString(" ON ")
  2672. _, _ = buf.WriteString(QuoteIdent(s.Database))
  2673. }
  2674. if s.Sources != nil {
  2675. _, _ = buf.WriteString(" FROM ")
  2676. _, _ = buf.WriteString(s.Sources.String())
  2677. }
  2678. _, _ = buf.WriteString(" WITH KEY ")
  2679. _, _ = buf.WriteString(s.Op.String())
  2680. _, _ = buf.WriteString(" ")
  2681. if lit, ok := s.TagKeyExpr.(*StringLiteral); ok {
  2682. _, _ = buf.WriteString(QuoteIdent(lit.Val))
  2683. } else {
  2684. _, _ = buf.WriteString(s.TagKeyExpr.String())
  2685. }
  2686. if s.Condition != nil {
  2687. _, _ = buf.WriteString(" WHERE ")
  2688. _, _ = buf.WriteString(s.Condition.String())
  2689. }
  2690. if len(s.Dimensions) > 0 {
  2691. _, _ = buf.WriteString(" GROUP BY ")
  2692. _, _ = buf.WriteString(s.Dimensions.String())
  2693. }
  2694. if s.Limit > 0 {
  2695. _, _ = fmt.Fprintf(&buf, " LIMIT %d", s.Limit)
  2696. }
  2697. if s.Offset > 0 {
  2698. _, _ = buf.WriteString(" OFFSET ")
  2699. _, _ = buf.WriteString(strconv.Itoa(s.Offset))
  2700. }
  2701. return buf.String()
  2702. }
  2703. // RequiredPrivileges returns the privilege required to execute a ShowTagValuesCardinalityStatement.
  2704. func (s *ShowTagValuesCardinalityStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  2705. return s.Sources.RequiredPrivileges()
  2706. }
  2707. // DefaultDatabase returns the default database from the statement.
  2708. func (s *ShowTagValuesCardinalityStatement) DefaultDatabase() string {
  2709. return s.Database
  2710. }
  2711. // ShowUsersStatement represents a command for listing users.
  2712. type ShowUsersStatement struct{}
  2713. // String returns a string representation of the ShowUsersStatement.
  2714. func (s *ShowUsersStatement) String() string {
  2715. return "SHOW USERS"
  2716. }
  2717. // RequiredPrivileges returns the privilege(s) required to execute a ShowUsersStatement
  2718. func (s *ShowUsersStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  2719. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}, nil
  2720. }
  2721. // ShowFieldKeyCardinalityStatement represents a command for listing field key cardinality.
  2722. type ShowFieldKeyCardinalityStatement struct {
  2723. Database string
  2724. Exact bool
  2725. Sources Sources
  2726. Condition Expr
  2727. Dimensions Dimensions
  2728. Limit, Offset int
  2729. }
  2730. // String returns a string representation of the statement.
  2731. func (s *ShowFieldKeyCardinalityStatement) String() string {
  2732. var buf bytes.Buffer
  2733. _, _ = buf.WriteString("SHOW FIELD KEY ")
  2734. if s.Exact {
  2735. _, _ = buf.WriteString("EXACT ")
  2736. }
  2737. _, _ = buf.WriteString("CARDINALITY")
  2738. if s.Database != "" {
  2739. _, _ = buf.WriteString(" ON ")
  2740. _, _ = buf.WriteString(QuoteIdent(s.Database))
  2741. }
  2742. if s.Sources != nil {
  2743. _, _ = buf.WriteString(" FROM ")
  2744. _, _ = buf.WriteString(s.Sources.String())
  2745. }
  2746. if s.Condition != nil {
  2747. _, _ = buf.WriteString(" WHERE ")
  2748. _, _ = buf.WriteString(s.Condition.String())
  2749. }
  2750. if len(s.Dimensions) > 0 {
  2751. _, _ = buf.WriteString(" GROUP BY ")
  2752. _, _ = buf.WriteString(s.Dimensions.String())
  2753. }
  2754. if s.Limit > 0 {
  2755. _, _ = fmt.Fprintf(&buf, " LIMIT %d", s.Limit)
  2756. }
  2757. if s.Offset > 0 {
  2758. _, _ = buf.WriteString(" OFFSET ")
  2759. _, _ = buf.WriteString(strconv.Itoa(s.Offset))
  2760. }
  2761. return buf.String()
  2762. }
  2763. // RequiredPrivileges returns the privilege required to execute a ShowFieldKeyCardinalityStatement.
  2764. func (s *ShowFieldKeyCardinalityStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  2765. return s.Sources.RequiredPrivileges()
  2766. }
  2767. // DefaultDatabase returns the default database from the statement.
  2768. func (s *ShowFieldKeyCardinalityStatement) DefaultDatabase() string {
  2769. return s.Database
  2770. }
  2771. // ShowFieldKeysStatement represents a command for listing field keys.
  2772. type ShowFieldKeysStatement struct {
  2773. // Database to query. If blank, use the default database.
  2774. // The database can also be specified per source in the Sources.
  2775. Database string
  2776. // Data sources that fields are extracted from.
  2777. Sources Sources
  2778. // Fields to sort results by
  2779. SortFields SortFields
  2780. // Maximum number of rows to be returned.
  2781. // Unlimited if zero.
  2782. Limit int
  2783. // Returns rows starting at an offset from the first row.
  2784. Offset int
  2785. }
  2786. // String returns a string representation of the statement.
  2787. func (s *ShowFieldKeysStatement) String() string {
  2788. var buf bytes.Buffer
  2789. _, _ = buf.WriteString("SHOW FIELD KEYS")
  2790. if s.Database != "" {
  2791. _, _ = buf.WriteString(" ON ")
  2792. _, _ = buf.WriteString(QuoteIdent(s.Database))
  2793. }
  2794. if s.Sources != nil {
  2795. _, _ = buf.WriteString(" FROM ")
  2796. _, _ = buf.WriteString(s.Sources.String())
  2797. }
  2798. if len(s.SortFields) > 0 {
  2799. _, _ = buf.WriteString(" ORDER BY ")
  2800. _, _ = buf.WriteString(s.SortFields.String())
  2801. }
  2802. if s.Limit > 0 {
  2803. _, _ = buf.WriteString(" LIMIT ")
  2804. _, _ = buf.WriteString(strconv.Itoa(s.Limit))
  2805. }
  2806. if s.Offset > 0 {
  2807. _, _ = buf.WriteString(" OFFSET ")
  2808. _, _ = buf.WriteString(strconv.Itoa(s.Offset))
  2809. }
  2810. return buf.String()
  2811. }
  2812. // RequiredPrivileges returns the privilege(s) required to execute a ShowFieldKeysStatement.
  2813. func (s *ShowFieldKeysStatement) RequiredPrivileges() (ExecutionPrivileges, error) {
  2814. return ExecutionPrivileges{{Admin: false, Name: s.Database, Privilege: ReadPrivilege}}, nil
  2815. }
  2816. // DefaultDatabase returns the default database from the statement.
  2817. func (s *ShowFieldKeysStatement) DefaultDatabase() string {
  2818. return s.Database
  2819. }
  2820. // Fields represents a list of fields.
  2821. type Fields []*Field
  2822. // AliasNames returns a list of calculated field names in
  2823. // order of alias, function name, then field.
  2824. func (a Fields) AliasNames() []string {
  2825. names := []string{}
  2826. for _, f := range a {
  2827. names = append(names, f.Name())
  2828. }
  2829. return names
  2830. }
  2831. // Names returns a list of field names.
  2832. func (a Fields) Names() []string {
  2833. names := []string{}
  2834. for _, f := range a {
  2835. switch expr := f.Expr.(type) {
  2836. case *Call:
  2837. names = append(names, expr.Name)
  2838. case *VarRef:
  2839. names = append(names, expr.Val)
  2840. case *BinaryExpr:
  2841. names = append(names, walkNames(expr)...)
  2842. case *ParenExpr:
  2843. names = append(names, walkNames(expr)...)
  2844. }
  2845. }
  2846. return names
  2847. }
  2848. // String returns a string representation of the fields.
  2849. func (a Fields) String() string {
  2850. var str []string
  2851. for _, f := range a {
  2852. str = append(str, f.String())
  2853. }
  2854. return strings.Join(str, ", ")
  2855. }
  2856. // Field represents an expression retrieved from a select statement.
  2857. type Field struct {
  2858. Expr Expr
  2859. Alias string
  2860. }
  2861. // Name returns the name of the field. Returns alias, if set.
  2862. // Otherwise uses the function name or variable name.
  2863. func (f *Field) Name() string {
  2864. // Return alias, if set.
  2865. if f.Alias != "" {
  2866. return f.Alias
  2867. }
  2868. // Return the function name or variable name, if available.
  2869. switch expr := f.Expr.(type) {
  2870. case *Call:
  2871. return expr.Name
  2872. case *BinaryExpr:
  2873. return BinaryExprName(expr)
  2874. case *ParenExpr:
  2875. f := Field{Expr: expr.Expr}
  2876. return f.Name()
  2877. case *VarRef:
  2878. return expr.Val
  2879. }
  2880. // Otherwise return a blank name.
  2881. return ""
  2882. }
  2883. // String returns a string representation of the field.
  2884. func (f *Field) String() string {
  2885. str := f.Expr.String()
  2886. if f.Alias == "" {
  2887. return str
  2888. }
  2889. return fmt.Sprintf("%s AS %s", str, QuoteIdent(f.Alias))
  2890. }
  2891. // Len implements sort.Interface.
  2892. func (a Fields) Len() int { return len(a) }
  2893. // Less implements sort.Interface.
  2894. func (a Fields) Less(i, j int) bool { return a[i].Name() < a[j].Name() }
  2895. // Swap implements sort.Interface.
  2896. func (a Fields) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  2897. // Dimensions represents a list of dimensions.
  2898. type Dimensions []*Dimension
  2899. // String returns a string representation of the dimensions.
  2900. func (a Dimensions) String() string {
  2901. var str []string
  2902. for _, d := range a {
  2903. str = append(str, d.String())
  2904. }
  2905. return strings.Join(str, ", ")
  2906. }
  2907. // Normalize returns the interval and tag dimensions separately.
  2908. // Returns 0 if no time interval is specified.
  2909. func (a Dimensions) Normalize() (time.Duration, []string) {
  2910. var dur time.Duration
  2911. var tags []string
  2912. for _, dim := range a {
  2913. switch expr := dim.Expr.(type) {
  2914. case *Call:
  2915. lit, _ := expr.Args[0].(*DurationLiteral)
  2916. dur = lit.Val
  2917. case *VarRef:
  2918. tags = append(tags, expr.Val)
  2919. }
  2920. }
  2921. return dur, tags
  2922. }
  2923. // Dimension represents an expression that a select statement is grouped by.
  2924. type Dimension struct {
  2925. Expr Expr
  2926. }
  2927. // String returns a string representation of the dimension.
  2928. func (d *Dimension) String() string { return d.Expr.String() }
  2929. // Measurements represents a list of measurements.
  2930. type Measurements []*Measurement
  2931. // String returns a string representation of the measurements.
  2932. func (a Measurements) String() string {
  2933. var str []string
  2934. for _, m := range a {
  2935. str = append(str, m.String())
  2936. }
  2937. return strings.Join(str, ", ")
  2938. }
  2939. // Measurement represents a single measurement used as a datasource.
  2940. type Measurement struct {
  2941. Database string
  2942. RetentionPolicy string
  2943. Name string
  2944. Regex *RegexLiteral
  2945. IsTarget bool
  2946. // This field indicates that the measurement should read be read from the
  2947. // specified system iterator.
  2948. SystemIterator string
  2949. }
  2950. // Clone returns a deep clone of the Measurement.
  2951. func (m *Measurement) Clone() *Measurement {
  2952. var regexp *RegexLiteral
  2953. if m.Regex != nil && m.Regex.Val != nil {
  2954. regexp = &RegexLiteral{Val: m.Regex.Val.Copy()}
  2955. }
  2956. return &Measurement{
  2957. Database: m.Database,
  2958. RetentionPolicy: m.RetentionPolicy,
  2959. Name: m.Name,
  2960. Regex: regexp,
  2961. IsTarget: m.IsTarget,
  2962. SystemIterator: m.SystemIterator,
  2963. }
  2964. }
  2965. // String returns a string representation of the measurement.
  2966. func (m *Measurement) String() string {
  2967. var buf bytes.Buffer
  2968. if m.Database != "" {
  2969. _, _ = buf.WriteString(QuoteIdent(m.Database))
  2970. _, _ = buf.WriteString(".")
  2971. }
  2972. if m.RetentionPolicy != "" {
  2973. _, _ = buf.WriteString(QuoteIdent(m.RetentionPolicy))
  2974. }
  2975. if m.Database != "" || m.RetentionPolicy != "" {
  2976. _, _ = buf.WriteString(`.`)
  2977. }
  2978. if m.Name != "" && m.SystemIterator == "" {
  2979. _, _ = buf.WriteString(QuoteIdent(m.Name))
  2980. } else if m.SystemIterator != "" {
  2981. _, _ = buf.WriteString(QuoteIdent(m.SystemIterator))
  2982. } else if m.Regex != nil {
  2983. _, _ = buf.WriteString(m.Regex.String())
  2984. }
  2985. return buf.String()
  2986. }
  2987. // SubQuery is a source with a SelectStatement as the backing store.
  2988. type SubQuery struct {
  2989. Statement *SelectStatement
  2990. }
  2991. // String returns a string representation of the subquery.
  2992. func (s *SubQuery) String() string {
  2993. return fmt.Sprintf("(%s)", s.Statement.String())
  2994. }
  2995. // VarRef represents a reference to a variable.
  2996. type VarRef struct {
  2997. Val string
  2998. Type DataType
  2999. }
  3000. // String returns a string representation of the variable reference.
  3001. func (r *VarRef) String() string {
  3002. buf := bytes.NewBufferString(QuoteIdent(r.Val))
  3003. if r.Type != Unknown {
  3004. buf.WriteString("::")
  3005. buf.WriteString(r.Type.String())
  3006. }
  3007. return buf.String()
  3008. }
  3009. // VarRefs represents a slice of VarRef types.
  3010. type VarRefs []VarRef
  3011. // Len implements sort.Interface.
  3012. func (a VarRefs) Len() int { return len(a) }
  3013. // Less implements sort.Interface.
  3014. func (a VarRefs) Less(i, j int) bool {
  3015. if a[i].Val != a[j].Val {
  3016. return a[i].Val < a[j].Val
  3017. }
  3018. return a[i].Type < a[j].Type
  3019. }
  3020. // Swap implements sort.Interface.
  3021. func (a VarRefs) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  3022. // Strings returns a slice of the variable names.
  3023. func (a VarRefs) Strings() []string {
  3024. s := make([]string, len(a))
  3025. for i, ref := range a {
  3026. s[i] = ref.Val
  3027. }
  3028. return s
  3029. }
  3030. // Call represents a function call.
  3031. type Call struct {
  3032. Name string
  3033. Args []Expr
  3034. }
  3035. // String returns a string representation of the call.
  3036. func (c *Call) String() string {
  3037. // Join arguments.
  3038. var str []string
  3039. for _, arg := range c.Args {
  3040. str = append(str, arg.String())
  3041. }
  3042. // Write function name and args.
  3043. return fmt.Sprintf("%s(%s)", c.Name, strings.Join(str, ", "))
  3044. }
  3045. // Distinct represents a DISTINCT expression.
  3046. type Distinct struct {
  3047. // Identifier following DISTINCT
  3048. Val string
  3049. }
  3050. // String returns a string representation of the expression.
  3051. func (d *Distinct) String() string {
  3052. return fmt.Sprintf("DISTINCT %s", d.Val)
  3053. }
  3054. // NewCall returns a new call expression from this expressions.
  3055. func (d *Distinct) NewCall() *Call {
  3056. return &Call{
  3057. Name: "distinct",
  3058. Args: []Expr{
  3059. &VarRef{Val: d.Val},
  3060. },
  3061. }
  3062. }
  3063. // NumberLiteral represents a numeric literal.
  3064. type NumberLiteral struct {
  3065. Val float64
  3066. }
  3067. // String returns a string representation of the literal.
  3068. func (l *NumberLiteral) String() string { return strconv.FormatFloat(l.Val, 'f', 3, 64) }
  3069. // IntegerLiteral represents an integer literal.
  3070. type IntegerLiteral struct {
  3071. Val int64
  3072. }
  3073. // String returns a string representation of the literal.
  3074. func (l *IntegerLiteral) String() string { return fmt.Sprintf("%d", l.Val) }
  3075. // UnsignedLiteral represents an unsigned literal. The parser will only use an unsigned literal if the parsed
  3076. // integer is greater than math.MaxInt64.
  3077. type UnsignedLiteral struct {
  3078. Val uint64
  3079. }
  3080. // String returns a string representation of the literal.
  3081. func (l *UnsignedLiteral) String() string { return strconv.FormatUint(l.Val, 10) }
  3082. // BooleanLiteral represents a boolean literal.
  3083. type BooleanLiteral struct {
  3084. Val bool
  3085. }
  3086. // String returns a string representation of the literal.
  3087. func (l *BooleanLiteral) String() string {
  3088. if l.Val {
  3089. return "true"
  3090. }
  3091. return "false"
  3092. }
  3093. // isTrueLiteral returns true if the expression is a literal "true" value.
  3094. func isTrueLiteral(expr Expr) bool {
  3095. if expr, ok := expr.(*BooleanLiteral); ok {
  3096. return expr.Val == true
  3097. }
  3098. return false
  3099. }
  3100. // isFalseLiteral returns true if the expression is a literal "false" value.
  3101. func isFalseLiteral(expr Expr) bool {
  3102. if expr, ok := expr.(*BooleanLiteral); ok {
  3103. return expr.Val == false
  3104. }
  3105. return false
  3106. }
  3107. // ListLiteral represents a list of tag key literals.
  3108. type ListLiteral struct {
  3109. Vals []string
  3110. }
  3111. // String returns a string representation of the literal.
  3112. func (s *ListLiteral) String() string {
  3113. var buf bytes.Buffer
  3114. _, _ = buf.WriteString("(")
  3115. for idx, tagKey := range s.Vals {
  3116. if idx != 0 {
  3117. _, _ = buf.WriteString(", ")
  3118. }
  3119. _, _ = buf.WriteString(QuoteIdent(tagKey))
  3120. }
  3121. _, _ = buf.WriteString(")")
  3122. return buf.String()
  3123. }
  3124. // StringLiteral represents a string literal.
  3125. type StringLiteral struct {
  3126. Val string
  3127. }
  3128. // String returns a string representation of the literal.
  3129. func (l *StringLiteral) String() string { return QuoteString(l.Val) }
  3130. // IsTimeLiteral returns if this string can be interpreted as a time literal.
  3131. func (l *StringLiteral) IsTimeLiteral() bool {
  3132. return isDateTimeString(l.Val) || isDateString(l.Val)
  3133. }
  3134. // ToTimeLiteral returns a time literal if this string can be converted to a time literal.
  3135. func (l *StringLiteral) ToTimeLiteral(loc *time.Location) (*TimeLiteral, error) {
  3136. if loc == nil {
  3137. loc = time.UTC
  3138. }
  3139. if isDateTimeString(l.Val) {
  3140. t, err := time.ParseInLocation(DateTimeFormat, l.Val, loc)
  3141. if err != nil {
  3142. // try to parse it as an RFCNano time
  3143. t, err = time.ParseInLocation(time.RFC3339Nano, l.Val, loc)
  3144. if err != nil {
  3145. return nil, ErrInvalidTime
  3146. }
  3147. }
  3148. return &TimeLiteral{Val: t}, nil
  3149. } else if isDateString(l.Val) {
  3150. t, err := time.ParseInLocation(DateFormat, l.Val, loc)
  3151. if err != nil {
  3152. return nil, ErrInvalidTime
  3153. }
  3154. return &TimeLiteral{Val: t}, nil
  3155. }
  3156. return nil, ErrInvalidTime
  3157. }
  3158. // TimeLiteral represents a point-in-time literal.
  3159. type TimeLiteral struct {
  3160. Val time.Time
  3161. }
  3162. // String returns a string representation of the literal.
  3163. func (l *TimeLiteral) String() string {
  3164. return `'` + l.Val.UTC().Format(time.RFC3339Nano) + `'`
  3165. }
  3166. // DurationLiteral represents a duration literal.
  3167. type DurationLiteral struct {
  3168. Val time.Duration
  3169. }
  3170. // String returns a string representation of the literal.
  3171. func (l *DurationLiteral) String() string { return FormatDuration(l.Val) }
  3172. // NilLiteral represents a nil literal.
  3173. // This is not available to the query language itself. It's only used internally.
  3174. type NilLiteral struct{}
  3175. // String returns a string representation of the literal.
  3176. func (l *NilLiteral) String() string { return `nil` }
  3177. // BoundParameter represents a bound parameter literal.
  3178. // This is not available to the query language itself, but can be used when
  3179. // constructing a query string from an AST.
  3180. type BoundParameter struct {
  3181. Name string
  3182. }
  3183. // String returns a string representation of the bound parameter.
  3184. func (bp *BoundParameter) String() string {
  3185. return fmt.Sprintf("$%s", QuoteIdent(bp.Name))
  3186. }
  3187. // BinaryExpr represents an operation between two expressions.
  3188. type BinaryExpr struct {
  3189. Op Token
  3190. LHS Expr
  3191. RHS Expr
  3192. }
  3193. // String returns a string representation of the binary expression.
  3194. func (e *BinaryExpr) String() string {
  3195. return fmt.Sprintf("%s %s %s", e.LHS.String(), e.Op.String(), e.RHS.String())
  3196. }
  3197. // BinaryExprName returns the name of a binary expression by concatenating
  3198. // the variables in the binary expression with underscores.
  3199. func BinaryExprName(expr *BinaryExpr) string {
  3200. v := binaryExprNameVisitor{}
  3201. Walk(&v, expr)
  3202. return strings.Join(v.names, "_")
  3203. }
  3204. type binaryExprNameVisitor struct {
  3205. names []string
  3206. }
  3207. func (v *binaryExprNameVisitor) Visit(n Node) Visitor {
  3208. switch n := n.(type) {
  3209. case *VarRef:
  3210. v.names = append(v.names, n.Val)
  3211. case *Call:
  3212. v.names = append(v.names, n.Name)
  3213. return nil
  3214. }
  3215. return v
  3216. }
  3217. // ParenExpr represents a parenthesized expression.
  3218. type ParenExpr struct {
  3219. Expr Expr
  3220. }
  3221. // String returns a string representation of the parenthesized expression.
  3222. func (e *ParenExpr) String() string { return fmt.Sprintf("(%s)", e.Expr.String()) }
  3223. // RegexLiteral represents a regular expression.
  3224. type RegexLiteral struct {
  3225. Val *regexp.Regexp
  3226. }
  3227. // String returns a string representation of the literal.
  3228. func (r *RegexLiteral) String() string {
  3229. if r.Val != nil {
  3230. return fmt.Sprintf("/%s/", strings.Replace(r.Val.String(), `/`, `\/`, -1))
  3231. }
  3232. return ""
  3233. }
  3234. // CloneRegexLiteral returns a clone of the RegexLiteral.
  3235. func CloneRegexLiteral(r *RegexLiteral) *RegexLiteral {
  3236. if r == nil {
  3237. return nil
  3238. }
  3239. clone := &RegexLiteral{}
  3240. if r.Val != nil {
  3241. clone.Val = regexp.MustCompile(r.Val.String())
  3242. }
  3243. return clone
  3244. }
  3245. // Wildcard represents a wild card expression.
  3246. type Wildcard struct {
  3247. Type Token
  3248. }
  3249. // String returns a string representation of the wildcard.
  3250. func (e *Wildcard) String() string {
  3251. switch e.Type {
  3252. case FIELD:
  3253. return "*::field"
  3254. case TAG:
  3255. return "*::tag"
  3256. default:
  3257. return "*"
  3258. }
  3259. }
  3260. // CloneExpr returns a deep copy of the expression.
  3261. func CloneExpr(expr Expr) Expr {
  3262. if expr == nil {
  3263. return nil
  3264. }
  3265. switch expr := expr.(type) {
  3266. case *BinaryExpr:
  3267. return &BinaryExpr{Op: expr.Op, LHS: CloneExpr(expr.LHS), RHS: CloneExpr(expr.RHS)}
  3268. case *BooleanLiteral:
  3269. return &BooleanLiteral{Val: expr.Val}
  3270. case *Call:
  3271. args := make([]Expr, len(expr.Args))
  3272. for i, arg := range expr.Args {
  3273. args[i] = CloneExpr(arg)
  3274. }
  3275. return &Call{Name: expr.Name, Args: args}
  3276. case *Distinct:
  3277. return &Distinct{Val: expr.Val}
  3278. case *DurationLiteral:
  3279. return &DurationLiteral{Val: expr.Val}
  3280. case *IntegerLiteral:
  3281. return &IntegerLiteral{Val: expr.Val}
  3282. case *UnsignedLiteral:
  3283. return &UnsignedLiteral{Val: expr.Val}
  3284. case *NumberLiteral:
  3285. return &NumberLiteral{Val: expr.Val}
  3286. case *ParenExpr:
  3287. return &ParenExpr{Expr: CloneExpr(expr.Expr)}
  3288. case *RegexLiteral:
  3289. return &RegexLiteral{Val: expr.Val}
  3290. case *StringLiteral:
  3291. return &StringLiteral{Val: expr.Val}
  3292. case *TimeLiteral:
  3293. return &TimeLiteral{Val: expr.Val}
  3294. case *VarRef:
  3295. return &VarRef{Val: expr.Val, Type: expr.Type}
  3296. case *Wildcard:
  3297. return &Wildcard{Type: expr.Type}
  3298. }
  3299. panic("unreachable")
  3300. }
  3301. // HasTimeExpr returns true if the expression has a time term.
  3302. func HasTimeExpr(expr Expr) bool {
  3303. switch n := expr.(type) {
  3304. case *BinaryExpr:
  3305. if n.Op == AND || n.Op == OR {
  3306. return HasTimeExpr(n.LHS) || HasTimeExpr(n.RHS)
  3307. }
  3308. if ref, ok := n.LHS.(*VarRef); ok && strings.ToLower(ref.Val) == "time" {
  3309. return true
  3310. }
  3311. return false
  3312. case *ParenExpr:
  3313. // walk down the tree
  3314. return HasTimeExpr(n.Expr)
  3315. default:
  3316. return false
  3317. }
  3318. }
  3319. // Visitor can be called by Walk to traverse an AST hierarchy.
  3320. // The Visit() function is called once per node.
  3321. type Visitor interface {
  3322. Visit(Node) Visitor
  3323. }
  3324. // Walk traverses a node hierarchy in depth-first order.
  3325. func Walk(v Visitor, node Node) {
  3326. if node == nil {
  3327. return
  3328. }
  3329. if v = v.Visit(node); v == nil {
  3330. return
  3331. }
  3332. switch n := node.(type) {
  3333. case *BinaryExpr:
  3334. Walk(v, n.LHS)
  3335. Walk(v, n.RHS)
  3336. case *Call:
  3337. for _, expr := range n.Args {
  3338. Walk(v, expr)
  3339. }
  3340. case *CreateContinuousQueryStatement:
  3341. Walk(v, n.Source)
  3342. case *Dimension:
  3343. Walk(v, n.Expr)
  3344. case Dimensions:
  3345. for _, c := range n {
  3346. Walk(v, c)
  3347. }
  3348. case *DeleteSeriesStatement:
  3349. Walk(v, n.Sources)
  3350. Walk(v, n.Condition)
  3351. case *DropSeriesStatement:
  3352. Walk(v, n.Sources)
  3353. Walk(v, n.Condition)
  3354. case *ExplainStatement:
  3355. Walk(v, n.Statement)
  3356. case *Field:
  3357. Walk(v, n.Expr)
  3358. case Fields:
  3359. for _, c := range n {
  3360. Walk(v, c)
  3361. }
  3362. case *ParenExpr:
  3363. Walk(v, n.Expr)
  3364. case *Query:
  3365. Walk(v, n.Statements)
  3366. case *SelectStatement:
  3367. Walk(v, n.Fields)
  3368. Walk(v, n.Target)
  3369. Walk(v, n.Dimensions)
  3370. Walk(v, n.Sources)
  3371. Walk(v, n.Condition)
  3372. Walk(v, n.SortFields)
  3373. case *ShowFieldKeyCardinalityStatement:
  3374. Walk(v, n.Sources)
  3375. Walk(v, n.Condition)
  3376. case *ShowSeriesStatement:
  3377. Walk(v, n.Sources)
  3378. Walk(v, n.Condition)
  3379. case *ShowSeriesCardinalityStatement:
  3380. Walk(v, n.Sources)
  3381. Walk(v, n.Condition)
  3382. case *ShowMeasurementCardinalityStatement:
  3383. Walk(v, n.Sources)
  3384. Walk(v, n.Condition)
  3385. case *ShowTagKeyCardinalityStatement:
  3386. Walk(v, n.Sources)
  3387. Walk(v, n.Condition)
  3388. case *ShowTagKeysStatement:
  3389. Walk(v, n.Sources)
  3390. Walk(v, n.Condition)
  3391. Walk(v, n.SortFields)
  3392. case *ShowTagValuesCardinalityStatement:
  3393. Walk(v, n.Sources)
  3394. Walk(v, n.Condition)
  3395. case *ShowTagValuesStatement:
  3396. Walk(v, n.Sources)
  3397. Walk(v, n.Condition)
  3398. Walk(v, n.SortFields)
  3399. case *ShowFieldKeysStatement:
  3400. Walk(v, n.Sources)
  3401. Walk(v, n.SortFields)
  3402. case SortFields:
  3403. for _, sf := range n {
  3404. Walk(v, sf)
  3405. }
  3406. case Sources:
  3407. for _, s := range n {
  3408. Walk(v, s)
  3409. }
  3410. case *SubQuery:
  3411. Walk(v, n.Statement)
  3412. case Statements:
  3413. for _, s := range n {
  3414. Walk(v, s)
  3415. }
  3416. case *Target:
  3417. if n != nil {
  3418. Walk(v, n.Measurement)
  3419. }
  3420. }
  3421. }
  3422. // WalkFunc traverses a node hierarchy in depth-first order.
  3423. func WalkFunc(node Node, fn func(Node)) {
  3424. Walk(walkFuncVisitor(fn), node)
  3425. }
  3426. type walkFuncVisitor func(Node)
  3427. func (fn walkFuncVisitor) Visit(n Node) Visitor { fn(n); return fn }
  3428. // Rewriter can be called by Rewrite to replace nodes in the AST hierarchy.
  3429. // The Rewrite() function is called once per node.
  3430. type Rewriter interface {
  3431. Rewrite(Node) Node
  3432. }
  3433. // Rewrite recursively invokes the rewriter to replace each node.
  3434. // Nodes are traversed depth-first and rewritten from leaf to root.
  3435. func Rewrite(r Rewriter, node Node) Node {
  3436. switch n := node.(type) {
  3437. case *Query:
  3438. n.Statements = Rewrite(r, n.Statements).(Statements)
  3439. case Statements:
  3440. for i, s := range n {
  3441. n[i] = Rewrite(r, s).(Statement)
  3442. }
  3443. case *SelectStatement:
  3444. n.Fields = Rewrite(r, n.Fields).(Fields)
  3445. n.Dimensions = Rewrite(r, n.Dimensions).(Dimensions)
  3446. n.Sources = Rewrite(r, n.Sources).(Sources)
  3447. // Rewrite may return nil. Nil does not satisfy the Expr
  3448. // interface. We only assert the rewritten result to be an
  3449. // Expr if it is not nil:
  3450. if cond := Rewrite(r, n.Condition); cond != nil {
  3451. n.Condition = cond.(Expr)
  3452. } else {
  3453. n.Condition = nil
  3454. }
  3455. case *SubQuery:
  3456. n.Statement = Rewrite(r, n.Statement).(*SelectStatement)
  3457. case Fields:
  3458. for i, f := range n {
  3459. n[i] = Rewrite(r, f).(*Field)
  3460. }
  3461. case *Field:
  3462. n.Expr = Rewrite(r, n.Expr).(Expr)
  3463. case Dimensions:
  3464. for i, d := range n {
  3465. n[i] = Rewrite(r, d).(*Dimension)
  3466. }
  3467. case *Dimension:
  3468. n.Expr = Rewrite(r, n.Expr).(Expr)
  3469. case *BinaryExpr:
  3470. n.LHS = Rewrite(r, n.LHS).(Expr)
  3471. n.RHS = Rewrite(r, n.RHS).(Expr)
  3472. case *ParenExpr:
  3473. n.Expr = Rewrite(r, n.Expr).(Expr)
  3474. case *Call:
  3475. for i, expr := range n.Args {
  3476. n.Args[i] = Rewrite(r, expr).(Expr)
  3477. }
  3478. }
  3479. return r.Rewrite(node)
  3480. }
  3481. // RewriteFunc rewrites a node hierarchy.
  3482. func RewriteFunc(node Node, fn func(Node) Node) Node {
  3483. return Rewrite(rewriterFunc(fn), node)
  3484. }
  3485. type rewriterFunc func(Node) Node
  3486. func (fn rewriterFunc) Rewrite(n Node) Node { return fn(n) }
  3487. // RewriteExpr recursively invokes the function to replace each expr.
  3488. // Nodes are traversed depth-first and rewritten from leaf to root.
  3489. func RewriteExpr(expr Expr, fn func(Expr) Expr) Expr {
  3490. switch e := expr.(type) {
  3491. case *BinaryExpr:
  3492. e.LHS = RewriteExpr(e.LHS, fn)
  3493. e.RHS = RewriteExpr(e.RHS, fn)
  3494. if e.LHS != nil && e.RHS == nil {
  3495. expr = e.LHS
  3496. } else if e.RHS != nil && e.LHS == nil {
  3497. expr = e.RHS
  3498. } else if e.LHS == nil && e.RHS == nil {
  3499. return nil
  3500. }
  3501. case *ParenExpr:
  3502. e.Expr = RewriteExpr(e.Expr, fn)
  3503. if e.Expr == nil {
  3504. return nil
  3505. }
  3506. case *Call:
  3507. for i, expr := range e.Args {
  3508. e.Args[i] = RewriteExpr(expr, fn)
  3509. }
  3510. }
  3511. return fn(expr)
  3512. }
  3513. // Eval evaluates expr against a map.
  3514. func Eval(expr Expr, m map[string]interface{}) interface{} {
  3515. eval := ValuerEval{Valuer: MapValuer(m)}
  3516. return eval.Eval(expr)
  3517. }
  3518. // MapValuer is a valuer that substitutes values for the mapped interface.
  3519. type MapValuer map[string]interface{}
  3520. // Value returns the value for a key in the MapValuer.
  3521. func (m MapValuer) Value(key string) (interface{}, bool) {
  3522. v, ok := m[key]
  3523. return v, ok
  3524. }
  3525. // ValuerEval will evaluate an expression using the Valuer.
  3526. type ValuerEval struct {
  3527. Valuer Valuer
  3528. // IntegerFloatDivision will set the eval system to treat
  3529. // a division between two integers as a floating point division.
  3530. IntegerFloatDivision bool
  3531. }
  3532. // Eval evaluates an expression and returns a value.
  3533. func (v *ValuerEval) Eval(expr Expr) interface{} {
  3534. if expr == nil {
  3535. return nil
  3536. }
  3537. switch expr := expr.(type) {
  3538. case *BinaryExpr:
  3539. return v.evalBinaryExpr(expr)
  3540. case *BooleanLiteral:
  3541. return expr.Val
  3542. case *IntegerLiteral:
  3543. return expr.Val
  3544. case *NumberLiteral:
  3545. return expr.Val
  3546. case *UnsignedLiteral:
  3547. return expr.Val
  3548. case *ParenExpr:
  3549. return v.Eval(expr.Expr)
  3550. case *RegexLiteral:
  3551. return expr.Val
  3552. case *StringLiteral:
  3553. return expr.Val
  3554. case *Call:
  3555. if valuer, ok := v.Valuer.(CallValuer); ok {
  3556. var args []interface{}
  3557. if len(expr.Args) > 0 {
  3558. args = make([]interface{}, len(expr.Args))
  3559. for i := range expr.Args {
  3560. args[i] = v.Eval(expr.Args[i])
  3561. }
  3562. }
  3563. val, _ := valuer.Call(expr.Name, args)
  3564. return val
  3565. }
  3566. return nil
  3567. case *VarRef:
  3568. val, _ := v.Valuer.Value(expr.Val)
  3569. return val
  3570. default:
  3571. return nil
  3572. }
  3573. }
  3574. // EvalBool evaluates expr and returns true if result is a boolean true.
  3575. // Otherwise returns false.
  3576. func (v *ValuerEval) EvalBool(expr Expr) bool {
  3577. val, _ := v.Eval(expr).(bool)
  3578. return val
  3579. }
  3580. func (v *ValuerEval) evalBinaryExpr(expr *BinaryExpr) interface{} {
  3581. lhs := v.Eval(expr.LHS)
  3582. rhs := v.Eval(expr.RHS)
  3583. if lhs == nil && rhs != nil {
  3584. // When the LHS is nil and the RHS is a boolean, implicitly cast the
  3585. // nil to false.
  3586. if _, ok := rhs.(bool); ok {
  3587. lhs = false
  3588. }
  3589. } else if lhs != nil && rhs == nil {
  3590. // Implicit cast of the RHS nil to false when the LHS is a boolean.
  3591. if _, ok := lhs.(bool); ok {
  3592. rhs = false
  3593. }
  3594. }
  3595. // Evaluate if both sides are simple types.
  3596. switch lhs := lhs.(type) {
  3597. case bool:
  3598. rhs, ok := rhs.(bool)
  3599. switch expr.Op {
  3600. case AND:
  3601. return ok && (lhs && rhs)
  3602. case OR:
  3603. return ok && (lhs || rhs)
  3604. case BITWISE_AND:
  3605. return ok && (lhs && rhs)
  3606. case BITWISE_OR:
  3607. return ok && (lhs || rhs)
  3608. case BITWISE_XOR:
  3609. return ok && (lhs != rhs)
  3610. case EQ:
  3611. return ok && (lhs == rhs)
  3612. case NEQ:
  3613. return ok && (lhs != rhs)
  3614. }
  3615. case float64:
  3616. // Try the rhs as a float64, int64, or uint64
  3617. rhsf, ok := rhs.(float64)
  3618. if !ok {
  3619. switch val := rhs.(type) {
  3620. case int64:
  3621. rhsf, ok = float64(val), true
  3622. case uint64:
  3623. rhsf, ok = float64(val), true
  3624. }
  3625. }
  3626. rhs := rhsf
  3627. switch expr.Op {
  3628. case EQ:
  3629. return ok && (lhs == rhs)
  3630. case NEQ:
  3631. return ok && (lhs != rhs)
  3632. case LT:
  3633. return ok && (lhs < rhs)
  3634. case LTE:
  3635. return ok && (lhs <= rhs)
  3636. case GT:
  3637. return ok && (lhs > rhs)
  3638. case GTE:
  3639. return ok && (lhs >= rhs)
  3640. case ADD:
  3641. if !ok {
  3642. return nil
  3643. }
  3644. return lhs + rhs
  3645. case SUB:
  3646. if !ok {
  3647. return nil
  3648. }
  3649. return lhs - rhs
  3650. case MUL:
  3651. if !ok {
  3652. return nil
  3653. }
  3654. return lhs * rhs
  3655. case DIV:
  3656. if !ok {
  3657. return nil
  3658. } else if rhs == 0 {
  3659. return float64(0)
  3660. }
  3661. return lhs / rhs
  3662. case MOD:
  3663. if !ok {
  3664. return nil
  3665. }
  3666. return math.Mod(lhs, rhs)
  3667. }
  3668. case int64:
  3669. // Try as a float64 to see if a float cast is required.
  3670. switch rhs := rhs.(type) {
  3671. case float64:
  3672. lhs := float64(lhs)
  3673. switch expr.Op {
  3674. case EQ:
  3675. return lhs == rhs
  3676. case NEQ:
  3677. return lhs != rhs
  3678. case LT:
  3679. return lhs < rhs
  3680. case LTE:
  3681. return lhs <= rhs
  3682. case GT:
  3683. return lhs > rhs
  3684. case GTE:
  3685. return lhs >= rhs
  3686. case ADD:
  3687. return lhs + rhs
  3688. case SUB:
  3689. return lhs - rhs
  3690. case MUL:
  3691. return lhs * rhs
  3692. case DIV:
  3693. if rhs == 0 {
  3694. return float64(0)
  3695. }
  3696. return lhs / rhs
  3697. case MOD:
  3698. return math.Mod(lhs, rhs)
  3699. }
  3700. case int64:
  3701. switch expr.Op {
  3702. case EQ:
  3703. return lhs == rhs
  3704. case NEQ:
  3705. return lhs != rhs
  3706. case LT:
  3707. return lhs < rhs
  3708. case LTE:
  3709. return lhs <= rhs
  3710. case GT:
  3711. return lhs > rhs
  3712. case GTE:
  3713. return lhs >= rhs
  3714. case ADD:
  3715. return lhs + rhs
  3716. case SUB:
  3717. return lhs - rhs
  3718. case MUL:
  3719. return lhs * rhs
  3720. case DIV:
  3721. if v.IntegerFloatDivision {
  3722. if rhs == 0 {
  3723. return float64(0)
  3724. }
  3725. return float64(lhs) / float64(rhs)
  3726. }
  3727. if rhs == 0 {
  3728. return int64(0)
  3729. }
  3730. return lhs / rhs
  3731. case MOD:
  3732. if rhs == 0 {
  3733. return int64(0)
  3734. }
  3735. return lhs % rhs
  3736. case BITWISE_AND:
  3737. return lhs & rhs
  3738. case BITWISE_OR:
  3739. return lhs | rhs
  3740. case BITWISE_XOR:
  3741. return lhs ^ rhs
  3742. }
  3743. case uint64:
  3744. switch expr.Op {
  3745. case EQ:
  3746. return uint64(lhs) == rhs
  3747. case NEQ:
  3748. return uint64(lhs) != rhs
  3749. case LT:
  3750. if lhs < 0 {
  3751. return true
  3752. }
  3753. return uint64(lhs) < rhs
  3754. case LTE:
  3755. if lhs < 0 {
  3756. return true
  3757. }
  3758. return uint64(lhs) <= rhs
  3759. case GT:
  3760. if lhs < 0 {
  3761. return false
  3762. }
  3763. return uint64(lhs) > rhs
  3764. case GTE:
  3765. if lhs < 0 {
  3766. return false
  3767. }
  3768. return uint64(lhs) >= rhs
  3769. case ADD:
  3770. return uint64(lhs) + rhs
  3771. case SUB:
  3772. return uint64(lhs) - rhs
  3773. case MUL:
  3774. return uint64(lhs) * rhs
  3775. case DIV:
  3776. if rhs == 0 {
  3777. return uint64(0)
  3778. }
  3779. return uint64(lhs) / rhs
  3780. case MOD:
  3781. if rhs == 0 {
  3782. return uint64(0)
  3783. }
  3784. return uint64(lhs) % rhs
  3785. case BITWISE_AND:
  3786. return uint64(lhs) & rhs
  3787. case BITWISE_OR:
  3788. return uint64(lhs) | rhs
  3789. case BITWISE_XOR:
  3790. return uint64(lhs) ^ rhs
  3791. }
  3792. }
  3793. case uint64:
  3794. // Try as a float64 to see if a float cast is required.
  3795. switch rhs := rhs.(type) {
  3796. case float64:
  3797. lhs := float64(lhs)
  3798. switch expr.Op {
  3799. case EQ:
  3800. return lhs == rhs
  3801. case NEQ:
  3802. return lhs != rhs
  3803. case LT:
  3804. return lhs < rhs
  3805. case LTE:
  3806. return lhs <= rhs
  3807. case GT:
  3808. return lhs > rhs
  3809. case GTE:
  3810. return lhs >= rhs
  3811. case ADD:
  3812. return lhs + rhs
  3813. case SUB:
  3814. return lhs - rhs
  3815. case MUL:
  3816. return lhs * rhs
  3817. case DIV:
  3818. if rhs == 0 {
  3819. return float64(0)
  3820. }
  3821. return lhs / rhs
  3822. case MOD:
  3823. return math.Mod(lhs, rhs)
  3824. }
  3825. case int64:
  3826. switch expr.Op {
  3827. case EQ:
  3828. return lhs == uint64(rhs)
  3829. case NEQ:
  3830. return lhs != uint64(rhs)
  3831. case LT:
  3832. if rhs < 0 {
  3833. return false
  3834. }
  3835. return lhs < uint64(rhs)
  3836. case LTE:
  3837. if rhs < 0 {
  3838. return false
  3839. }
  3840. return lhs <= uint64(rhs)
  3841. case GT:
  3842. if rhs < 0 {
  3843. return true
  3844. }
  3845. return lhs > uint64(rhs)
  3846. case GTE:
  3847. if rhs < 0 {
  3848. return true
  3849. }
  3850. return lhs >= uint64(rhs)
  3851. case ADD:
  3852. return lhs + uint64(rhs)
  3853. case SUB:
  3854. return lhs - uint64(rhs)
  3855. case MUL:
  3856. return lhs * uint64(rhs)
  3857. case DIV:
  3858. if rhs == 0 {
  3859. return uint64(0)
  3860. }
  3861. return lhs / uint64(rhs)
  3862. case MOD:
  3863. if rhs == 0 {
  3864. return uint64(0)
  3865. }
  3866. return lhs % uint64(rhs)
  3867. case BITWISE_AND:
  3868. return lhs & uint64(rhs)
  3869. case BITWISE_OR:
  3870. return lhs | uint64(rhs)
  3871. case BITWISE_XOR:
  3872. return lhs ^ uint64(rhs)
  3873. }
  3874. case uint64:
  3875. switch expr.Op {
  3876. case EQ:
  3877. return lhs == rhs
  3878. case NEQ:
  3879. return lhs != rhs
  3880. case LT:
  3881. return lhs < rhs
  3882. case LTE:
  3883. return lhs <= rhs
  3884. case GT:
  3885. return lhs > rhs
  3886. case GTE:
  3887. return lhs >= rhs
  3888. case ADD:
  3889. return lhs + rhs
  3890. case SUB:
  3891. return lhs - rhs
  3892. case MUL:
  3893. return lhs * rhs
  3894. case DIV:
  3895. if rhs == 0 {
  3896. return uint64(0)
  3897. }
  3898. return lhs / rhs
  3899. case MOD:
  3900. if rhs == 0 {
  3901. return uint64(0)
  3902. }
  3903. return lhs % rhs
  3904. case BITWISE_AND:
  3905. return lhs & rhs
  3906. case BITWISE_OR:
  3907. return lhs | rhs
  3908. case BITWISE_XOR:
  3909. return lhs ^ rhs
  3910. }
  3911. }
  3912. case string:
  3913. switch expr.Op {
  3914. case EQ:
  3915. rhs, ok := rhs.(string)
  3916. if !ok {
  3917. return false
  3918. }
  3919. return lhs == rhs
  3920. case NEQ:
  3921. rhs, ok := rhs.(string)
  3922. if !ok {
  3923. return false
  3924. }
  3925. return lhs != rhs
  3926. case EQREGEX:
  3927. rhs, ok := rhs.(*regexp.Regexp)
  3928. if !ok {
  3929. return false
  3930. }
  3931. return rhs.MatchString(lhs)
  3932. case NEQREGEX:
  3933. rhs, ok := rhs.(*regexp.Regexp)
  3934. if !ok {
  3935. return false
  3936. }
  3937. return !rhs.MatchString(lhs)
  3938. }
  3939. }
  3940. // The types were not comparable. If our operation was an equality operation,
  3941. // return false instead of true.
  3942. switch expr.Op {
  3943. case EQ, NEQ, LT, LTE, GT, GTE:
  3944. return false
  3945. }
  3946. return nil
  3947. }
  3948. // EvalBool evaluates expr and returns true if result is a boolean true.
  3949. // Otherwise returns false.
  3950. func EvalBool(expr Expr, m map[string]interface{}) bool {
  3951. v, _ := Eval(expr, m).(bool)
  3952. return v
  3953. }
  3954. // TypeMapper maps a data type to the measurement and field.
  3955. type TypeMapper interface {
  3956. MapType(measurement *Measurement, field string) DataType
  3957. }
  3958. // CallTypeMapper maps a data type to the function call.
  3959. type CallTypeMapper interface {
  3960. TypeMapper
  3961. CallType(name string, args []DataType) (DataType, error)
  3962. }
  3963. type nilTypeMapper struct{}
  3964. func (nilTypeMapper) MapType(*Measurement, string) DataType { return Unknown }
  3965. type multiTypeMapper []TypeMapper
  3966. // MultiTypeMapper combines multiple TypeMappers into a single one.
  3967. // The MultiTypeMapper will return the first type that is not Unknown.
  3968. // It will not iterate through all of them to find the highest priority one.
  3969. func MultiTypeMapper(mappers ...TypeMapper) TypeMapper {
  3970. return multiTypeMapper(mappers)
  3971. }
  3972. func (a multiTypeMapper) MapType(measurement *Measurement, field string) DataType {
  3973. for _, m := range a {
  3974. if typ := m.MapType(measurement, field); typ != Unknown {
  3975. return typ
  3976. }
  3977. }
  3978. return Unknown
  3979. }
  3980. func (a multiTypeMapper) CallType(name string, args []DataType) (DataType, error) {
  3981. for _, m := range a {
  3982. call, ok := m.(CallTypeMapper)
  3983. if ok {
  3984. typ, err := call.CallType(name, args)
  3985. if err != nil {
  3986. return Unknown, err
  3987. } else if typ != Unknown {
  3988. return typ, nil
  3989. }
  3990. }
  3991. }
  3992. return Unknown, nil
  3993. }
  3994. // TypeValuerEval evaluates an expression to determine its output type.
  3995. type TypeValuerEval struct {
  3996. TypeMapper TypeMapper
  3997. Sources Sources
  3998. }
  3999. // EvalType returns the type for an expression. If the expression cannot
  4000. // be evaluated for some reason, like incompatible types, it is returned
  4001. // as a TypeError in the error. If the error is non-fatal so we can continue
  4002. // even though an error happened, true will be returned.
  4003. // This function assumes that the expression has already been reduced.
  4004. func (v *TypeValuerEval) EvalType(expr Expr) (DataType, error) {
  4005. switch expr := expr.(type) {
  4006. case *VarRef:
  4007. return v.evalVarRefExprType(expr)
  4008. case *Call:
  4009. return v.evalCallExprType(expr)
  4010. case *BinaryExpr:
  4011. return v.evalBinaryExprType(expr)
  4012. case *ParenExpr:
  4013. return v.EvalType(expr.Expr)
  4014. case *NumberLiteral:
  4015. return Float, nil
  4016. case *IntegerLiteral:
  4017. return Integer, nil
  4018. case *UnsignedLiteral:
  4019. return Unsigned, nil
  4020. case *StringLiteral:
  4021. return String, nil
  4022. case *BooleanLiteral:
  4023. return Boolean, nil
  4024. }
  4025. return Unknown, nil
  4026. }
  4027. func (v *TypeValuerEval) evalVarRefExprType(expr *VarRef) (DataType, error) {
  4028. // If this variable already has an assigned type, just use that.
  4029. if expr.Type != Unknown && expr.Type != AnyField {
  4030. return expr.Type, nil
  4031. }
  4032. var typ DataType
  4033. if v.TypeMapper != nil {
  4034. for _, src := range v.Sources {
  4035. switch src := src.(type) {
  4036. case *Measurement:
  4037. if t := v.TypeMapper.MapType(src, expr.Val); typ.LessThan(t) {
  4038. typ = t
  4039. }
  4040. case *SubQuery:
  4041. _, e := src.Statement.FieldExprByName(expr.Val)
  4042. if e != nil {
  4043. valuer := TypeValuerEval{
  4044. TypeMapper: v.TypeMapper,
  4045. Sources: src.Statement.Sources,
  4046. }
  4047. if t, err := valuer.EvalType(e); err != nil {
  4048. return Unknown, err
  4049. } else if typ.LessThan(t) {
  4050. typ = t
  4051. }
  4052. }
  4053. if typ == Unknown {
  4054. for _, d := range src.Statement.Dimensions {
  4055. if d, ok := d.Expr.(*VarRef); ok && expr.Val == d.Val {
  4056. typ = Tag
  4057. }
  4058. }
  4059. }
  4060. }
  4061. }
  4062. }
  4063. return typ, nil
  4064. }
  4065. func (v *TypeValuerEval) evalCallExprType(expr *Call) (DataType, error) {
  4066. typmap, ok := v.TypeMapper.(CallTypeMapper)
  4067. if !ok {
  4068. return Unknown, nil
  4069. }
  4070. // Evaluate all of the data types for the arguments.
  4071. args := make([]DataType, len(expr.Args))
  4072. for i, arg := range expr.Args {
  4073. typ, err := v.EvalType(arg)
  4074. if err != nil {
  4075. return Unknown, err
  4076. }
  4077. args[i] = typ
  4078. }
  4079. // Pass in the data types for the call so it can be type checked and
  4080. // the resulting type can be returned.
  4081. return typmap.CallType(expr.Name, args)
  4082. }
  4083. func (v *TypeValuerEval) evalBinaryExprType(expr *BinaryExpr) (DataType, error) {
  4084. // Find the data type for both sides of the expression.
  4085. lhs, err := v.EvalType(expr.LHS)
  4086. if err != nil {
  4087. return Unknown, err
  4088. }
  4089. rhs, err := v.EvalType(expr.RHS)
  4090. if err != nil {
  4091. return Unknown, err
  4092. }
  4093. // If one of the two is unsigned and the other is an integer, we cannot add
  4094. // the two without an explicit cast unless the integer is a literal.
  4095. if lhs == Unsigned && rhs == Integer {
  4096. if isLiteral(expr.LHS) {
  4097. return Unknown, &TypeError{
  4098. Expr: expr,
  4099. Message: fmt.Sprintf("cannot use %s with an integer and unsigned literal", expr.Op),
  4100. }
  4101. } else if !isLiteral(expr.RHS) {
  4102. return Unknown, &TypeError{
  4103. Expr: expr,
  4104. Message: fmt.Sprintf("cannot use %s between an integer and unsigned, an explicit cast is required", expr.Op),
  4105. }
  4106. }
  4107. } else if lhs == Integer && rhs == Unsigned {
  4108. if isLiteral(expr.RHS) {
  4109. return Unknown, &TypeError{
  4110. Expr: expr,
  4111. Message: fmt.Sprintf("cannot use %s with an integer and unsigned literal", expr.Op),
  4112. }
  4113. } else if !isLiteral(expr.LHS) {
  4114. return Unknown, &TypeError{
  4115. Expr: expr,
  4116. Message: fmt.Sprintf("cannot use %s between an integer and unsigned, an explicit cast is required", expr.Op),
  4117. }
  4118. }
  4119. }
  4120. // If one of the two is unknown, then return the other as the type.
  4121. if lhs == Unknown {
  4122. return rhs, nil
  4123. } else if rhs == Unknown {
  4124. return lhs, nil
  4125. }
  4126. // Rather than re-implement the ValuerEval here, we create a dummy binary
  4127. // expression with the zero values and inspect the resulting value back into
  4128. // a data type to determine the output.
  4129. e := BinaryExpr{
  4130. LHS: &VarRef{Val: "lhs"},
  4131. RHS: &VarRef{Val: "rhs"},
  4132. Op: expr.Op,
  4133. }
  4134. result := Eval(&e, map[string]interface{}{
  4135. "lhs": lhs.Zero(),
  4136. "rhs": rhs.Zero(),
  4137. })
  4138. typ := InspectDataType(result)
  4139. if typ == Unknown {
  4140. // If the type is unknown, then the two types were not compatible.
  4141. return Unknown, &TypeError{
  4142. Expr: expr,
  4143. Message: fmt.Sprintf("incompatible types: %s and %s", lhs, rhs),
  4144. }
  4145. }
  4146. return typ, nil
  4147. }
  4148. // TypeError is an error when two types are incompatible.
  4149. type TypeError struct {
  4150. // Expr contains the expression that generated the type error.
  4151. Expr Expr
  4152. // Message contains the informational message about the type error.
  4153. Message string
  4154. }
  4155. func (e *TypeError) Error() string {
  4156. return fmt.Sprintf("type error: %s: %s", e.Expr, e.Message)
  4157. }
  4158. // EvalType evaluates the expression's type.
  4159. func EvalType(expr Expr, sources Sources, typmap TypeMapper) DataType {
  4160. if typmap == nil {
  4161. typmap = nilTypeMapper{}
  4162. }
  4163. valuer := TypeValuerEval{
  4164. TypeMapper: typmap,
  4165. Sources: sources,
  4166. }
  4167. typ, _ := valuer.EvalType(expr)
  4168. return typ
  4169. }
  4170. func FieldDimensions(sources Sources, m FieldMapper) (fields map[string]DataType, dimensions map[string]struct{}, err error) {
  4171. fields = make(map[string]DataType)
  4172. dimensions = make(map[string]struct{})
  4173. for _, src := range sources {
  4174. switch src := src.(type) {
  4175. case *Measurement:
  4176. f, d, err := m.FieldDimensions(src)
  4177. if err != nil {
  4178. return nil, nil, err
  4179. }
  4180. for k, typ := range f {
  4181. if fields[k].LessThan(typ) {
  4182. fields[k] = typ
  4183. }
  4184. }
  4185. for k := range d {
  4186. dimensions[k] = struct{}{}
  4187. }
  4188. case *SubQuery:
  4189. for _, f := range src.Statement.Fields {
  4190. k := f.Name()
  4191. typ := EvalType(f.Expr, src.Statement.Sources, m)
  4192. if fields[k].LessThan(typ) {
  4193. fields[k] = typ
  4194. }
  4195. }
  4196. for _, d := range src.Statement.Dimensions {
  4197. if expr, ok := d.Expr.(*VarRef); ok {
  4198. dimensions[expr.Val] = struct{}{}
  4199. }
  4200. }
  4201. }
  4202. }
  4203. return
  4204. }
  4205. // Reduce evaluates expr using the available values in valuer.
  4206. // References that don't exist in valuer are ignored.
  4207. func Reduce(expr Expr, valuer Valuer) Expr {
  4208. expr = reduce(expr, valuer)
  4209. // Unwrap parens at top level.
  4210. if expr, ok := expr.(*ParenExpr); ok {
  4211. return expr.Expr
  4212. }
  4213. return expr
  4214. }
  4215. func reduce(expr Expr, valuer Valuer) Expr {
  4216. if expr == nil {
  4217. return nil
  4218. }
  4219. switch expr := expr.(type) {
  4220. case *BinaryExpr:
  4221. return reduceBinaryExpr(expr, valuer)
  4222. case *Call:
  4223. return reduceCall(expr, valuer)
  4224. case *ParenExpr:
  4225. return reduceParenExpr(expr, valuer)
  4226. case *VarRef:
  4227. return reduceVarRef(expr, valuer)
  4228. case *NilLiteral:
  4229. return expr
  4230. default:
  4231. return CloneExpr(expr)
  4232. }
  4233. }
  4234. func reduceBinaryExpr(expr *BinaryExpr, valuer Valuer) Expr {
  4235. // Reduce both sides first.
  4236. op := expr.Op
  4237. lhs := reduce(expr.LHS, valuer)
  4238. rhs := reduce(expr.RHS, valuer)
  4239. loc := time.UTC
  4240. if valuer, ok := valuer.(ZoneValuer); ok {
  4241. if l := valuer.Zone(); l != nil {
  4242. loc = l
  4243. }
  4244. }
  4245. // Do not evaluate if one side is nil.
  4246. if lhs == nil || rhs == nil {
  4247. return &BinaryExpr{LHS: lhs, RHS: rhs, Op: expr.Op}
  4248. }
  4249. // If we have a logical operator (AND, OR) and one side is a boolean literal
  4250. // then we need to have special handling.
  4251. if op == AND {
  4252. if isFalseLiteral(lhs) || isFalseLiteral(rhs) {
  4253. return &BooleanLiteral{Val: false}
  4254. } else if isTrueLiteral(lhs) {
  4255. return rhs
  4256. } else if isTrueLiteral(rhs) {
  4257. return lhs
  4258. }
  4259. } else if op == OR {
  4260. if isTrueLiteral(lhs) || isTrueLiteral(rhs) {
  4261. return &BooleanLiteral{Val: true}
  4262. } else if isFalseLiteral(lhs) {
  4263. return rhs
  4264. } else if isFalseLiteral(rhs) {
  4265. return lhs
  4266. }
  4267. }
  4268. // Evaluate if both sides are simple types.
  4269. switch lhs := lhs.(type) {
  4270. case *BooleanLiteral:
  4271. return reduceBinaryExprBooleanLHS(op, lhs, rhs)
  4272. case *DurationLiteral:
  4273. return reduceBinaryExprDurationLHS(op, lhs, rhs, loc)
  4274. case *IntegerLiteral:
  4275. return reduceBinaryExprIntegerLHS(op, lhs, rhs, loc)
  4276. case *UnsignedLiteral:
  4277. return reduceBinaryExprUnsignedLHS(op, lhs, rhs)
  4278. case *NilLiteral:
  4279. return reduceBinaryExprNilLHS(op, lhs, rhs)
  4280. case *NumberLiteral:
  4281. return reduceBinaryExprNumberLHS(op, lhs, rhs)
  4282. case *StringLiteral:
  4283. return reduceBinaryExprStringLHS(op, lhs, rhs, loc)
  4284. case *TimeLiteral:
  4285. return reduceBinaryExprTimeLHS(op, lhs, rhs, loc)
  4286. default:
  4287. return &BinaryExpr{Op: op, LHS: lhs, RHS: rhs}
  4288. }
  4289. }
  4290. func reduceBinaryExprBooleanLHS(op Token, lhs *BooleanLiteral, rhs Expr) Expr {
  4291. switch rhs := rhs.(type) {
  4292. case *BooleanLiteral:
  4293. switch op {
  4294. case EQ:
  4295. return &BooleanLiteral{Val: lhs.Val == rhs.Val}
  4296. case NEQ:
  4297. return &BooleanLiteral{Val: lhs.Val != rhs.Val}
  4298. case AND:
  4299. return &BooleanLiteral{Val: lhs.Val && rhs.Val}
  4300. case OR:
  4301. return &BooleanLiteral{Val: lhs.Val || rhs.Val}
  4302. case BITWISE_AND:
  4303. return &BooleanLiteral{Val: lhs.Val && rhs.Val}
  4304. case BITWISE_OR:
  4305. return &BooleanLiteral{Val: lhs.Val || rhs.Val}
  4306. case BITWISE_XOR:
  4307. return &BooleanLiteral{Val: lhs.Val != rhs.Val}
  4308. }
  4309. case *NilLiteral:
  4310. return &BooleanLiteral{Val: false}
  4311. }
  4312. return &BinaryExpr{Op: op, LHS: lhs, RHS: rhs}
  4313. }
  4314. func reduceBinaryExprDurationLHS(op Token, lhs *DurationLiteral, rhs Expr, loc *time.Location) Expr {
  4315. switch rhs := rhs.(type) {
  4316. case *DurationLiteral:
  4317. switch op {
  4318. case ADD:
  4319. return &DurationLiteral{Val: lhs.Val + rhs.Val}
  4320. case SUB:
  4321. return &DurationLiteral{Val: lhs.Val - rhs.Val}
  4322. case EQ:
  4323. return &BooleanLiteral{Val: lhs.Val == rhs.Val}
  4324. case NEQ:
  4325. return &BooleanLiteral{Val: lhs.Val != rhs.Val}
  4326. case GT:
  4327. return &BooleanLiteral{Val: lhs.Val > rhs.Val}
  4328. case GTE:
  4329. return &BooleanLiteral{Val: lhs.Val >= rhs.Val}
  4330. case LT:
  4331. return &BooleanLiteral{Val: lhs.Val < rhs.Val}
  4332. case LTE:
  4333. return &BooleanLiteral{Val: lhs.Val <= rhs.Val}
  4334. }
  4335. case *NumberLiteral:
  4336. switch op {
  4337. case MUL:
  4338. return &DurationLiteral{Val: lhs.Val * time.Duration(rhs.Val)}
  4339. case DIV:
  4340. if rhs.Val == 0 {
  4341. return &DurationLiteral{Val: 0}
  4342. }
  4343. return &DurationLiteral{Val: lhs.Val / time.Duration(rhs.Val)}
  4344. }
  4345. case *IntegerLiteral:
  4346. switch op {
  4347. case MUL:
  4348. return &DurationLiteral{Val: lhs.Val * time.Duration(rhs.Val)}
  4349. case DIV:
  4350. if rhs.Val == 0 {
  4351. return &DurationLiteral{Val: 0}
  4352. }
  4353. return &DurationLiteral{Val: lhs.Val / time.Duration(rhs.Val)}
  4354. }
  4355. case *TimeLiteral:
  4356. switch op {
  4357. case ADD:
  4358. return &TimeLiteral{Val: rhs.Val.Add(lhs.Val)}
  4359. }
  4360. case *StringLiteral:
  4361. t, err := rhs.ToTimeLiteral(loc)
  4362. if err != nil {
  4363. break
  4364. }
  4365. expr := reduceBinaryExprDurationLHS(op, lhs, t, loc)
  4366. // If the returned expression is still a binary expr, that means
  4367. // we couldn't reduce it so this wasn't used in a time literal context.
  4368. if _, ok := expr.(*BinaryExpr); !ok {
  4369. return expr
  4370. }
  4371. case *NilLiteral:
  4372. return &BooleanLiteral{Val: false}
  4373. }
  4374. return &BinaryExpr{Op: op, LHS: lhs, RHS: rhs}
  4375. }
  4376. func reduceBinaryExprIntegerLHS(op Token, lhs *IntegerLiteral, rhs Expr, loc *time.Location) Expr {
  4377. switch rhs := rhs.(type) {
  4378. case *NumberLiteral:
  4379. return reduceBinaryExprNumberLHS(op, &NumberLiteral{Val: float64(lhs.Val)}, rhs)
  4380. case *IntegerLiteral:
  4381. switch op {
  4382. case ADD:
  4383. return &IntegerLiteral{Val: lhs.Val + rhs.Val}
  4384. case SUB:
  4385. return &IntegerLiteral{Val: lhs.Val - rhs.Val}
  4386. case MUL:
  4387. return &IntegerLiteral{Val: lhs.Val * rhs.Val}
  4388. case DIV:
  4389. if rhs.Val == 0 {
  4390. return &NumberLiteral{Val: 0}
  4391. }
  4392. return &NumberLiteral{Val: float64(lhs.Val) / float64(rhs.Val)}
  4393. case MOD:
  4394. if rhs.Val == 0 {
  4395. return &IntegerLiteral{Val: 0}
  4396. }
  4397. return &IntegerLiteral{Val: lhs.Val % rhs.Val}
  4398. case BITWISE_AND:
  4399. return &IntegerLiteral{Val: lhs.Val & rhs.Val}
  4400. case BITWISE_OR:
  4401. return &IntegerLiteral{Val: lhs.Val | rhs.Val}
  4402. case BITWISE_XOR:
  4403. return &IntegerLiteral{Val: lhs.Val ^ rhs.Val}
  4404. case EQ:
  4405. return &BooleanLiteral{Val: lhs.Val == rhs.Val}
  4406. case NEQ:
  4407. return &BooleanLiteral{Val: lhs.Val != rhs.Val}
  4408. case GT:
  4409. return &BooleanLiteral{Val: lhs.Val > rhs.Val}
  4410. case GTE:
  4411. return &BooleanLiteral{Val: lhs.Val >= rhs.Val}
  4412. case LT:
  4413. return &BooleanLiteral{Val: lhs.Val < rhs.Val}
  4414. case LTE:
  4415. return &BooleanLiteral{Val: lhs.Val <= rhs.Val}
  4416. }
  4417. case *UnsignedLiteral:
  4418. // Comparisons between an unsigned and integer literal will not involve
  4419. // a cast if the integer is negative as that will have an improper result.
  4420. // Look for those situations here.
  4421. if lhs.Val < 0 {
  4422. switch op {
  4423. case LT, LTE:
  4424. return &BooleanLiteral{Val: true}
  4425. case GT, GTE:
  4426. return &BooleanLiteral{Val: false}
  4427. }
  4428. }
  4429. return reduceBinaryExprUnsignedLHS(op, &UnsignedLiteral{Val: uint64(lhs.Val)}, rhs)
  4430. case *DurationLiteral:
  4431. // Treat the integer as a timestamp.
  4432. switch op {
  4433. case ADD:
  4434. return &TimeLiteral{Val: time.Unix(0, lhs.Val).Add(rhs.Val)}
  4435. case SUB:
  4436. return &TimeLiteral{Val: time.Unix(0, lhs.Val).Add(-rhs.Val)}
  4437. }
  4438. case *TimeLiteral:
  4439. d := &DurationLiteral{Val: time.Duration(lhs.Val)}
  4440. expr := reduceBinaryExprDurationLHS(op, d, rhs, loc)
  4441. if _, ok := expr.(*BinaryExpr); !ok {
  4442. return expr
  4443. }
  4444. case *StringLiteral:
  4445. t, err := rhs.ToTimeLiteral(loc)
  4446. if err != nil {
  4447. break
  4448. }
  4449. d := &DurationLiteral{Val: time.Duration(lhs.Val)}
  4450. expr := reduceBinaryExprDurationLHS(op, d, t, loc)
  4451. if _, ok := expr.(*BinaryExpr); !ok {
  4452. return expr
  4453. }
  4454. case *NilLiteral:
  4455. return &BooleanLiteral{Val: false}
  4456. }
  4457. return &BinaryExpr{Op: op, LHS: lhs, RHS: rhs}
  4458. }
  4459. func reduceBinaryExprUnsignedLHS(op Token, lhs *UnsignedLiteral, rhs Expr) Expr {
  4460. switch rhs := rhs.(type) {
  4461. case *NumberLiteral:
  4462. return reduceBinaryExprNumberLHS(op, &NumberLiteral{Val: float64(lhs.Val)}, rhs)
  4463. case *IntegerLiteral:
  4464. // Comparisons between an unsigned and integer literal will not involve
  4465. // a cast if the integer is negative as that will have an improper result.
  4466. // Look for those situations here.
  4467. if rhs.Val < 0 {
  4468. switch op {
  4469. case LT, LTE:
  4470. return &BooleanLiteral{Val: false}
  4471. case GT, GTE:
  4472. return &BooleanLiteral{Val: true}
  4473. }
  4474. }
  4475. return reduceBinaryExprUnsignedLHS(op, lhs, &UnsignedLiteral{Val: uint64(rhs.Val)})
  4476. case *UnsignedLiteral:
  4477. switch op {
  4478. case ADD:
  4479. return &UnsignedLiteral{Val: lhs.Val + rhs.Val}
  4480. case SUB:
  4481. return &UnsignedLiteral{Val: lhs.Val - rhs.Val}
  4482. case MUL:
  4483. return &UnsignedLiteral{Val: lhs.Val * rhs.Val}
  4484. case DIV:
  4485. if rhs.Val == 0 {
  4486. return &UnsignedLiteral{Val: 0}
  4487. }
  4488. return &UnsignedLiteral{Val: lhs.Val / rhs.Val}
  4489. case MOD:
  4490. if rhs.Val == 0 {
  4491. return &UnsignedLiteral{Val: 0}
  4492. }
  4493. return &UnsignedLiteral{Val: lhs.Val % rhs.Val}
  4494. case EQ:
  4495. return &BooleanLiteral{Val: lhs.Val == rhs.Val}
  4496. case NEQ:
  4497. return &BooleanLiteral{Val: lhs.Val != rhs.Val}
  4498. case GT:
  4499. return &BooleanLiteral{Val: lhs.Val > rhs.Val}
  4500. case GTE:
  4501. return &BooleanLiteral{Val: lhs.Val >= rhs.Val}
  4502. case LT:
  4503. return &BooleanLiteral{Val: lhs.Val < rhs.Val}
  4504. case LTE:
  4505. return &BooleanLiteral{Val: lhs.Val <= rhs.Val}
  4506. }
  4507. }
  4508. return &BinaryExpr{Op: op, LHS: lhs, RHS: rhs}
  4509. }
  4510. func reduceBinaryExprNilLHS(op Token, lhs *NilLiteral, rhs Expr) Expr {
  4511. switch op {
  4512. case EQ, NEQ:
  4513. return &BooleanLiteral{Val: false}
  4514. }
  4515. return &BinaryExpr{Op: op, LHS: lhs, RHS: rhs}
  4516. }
  4517. func reduceBinaryExprNumberLHS(op Token, lhs *NumberLiteral, rhs Expr) Expr {
  4518. switch rhs := rhs.(type) {
  4519. case *NumberLiteral:
  4520. switch op {
  4521. case ADD:
  4522. return &NumberLiteral{Val: lhs.Val + rhs.Val}
  4523. case SUB:
  4524. return &NumberLiteral{Val: lhs.Val - rhs.Val}
  4525. case MUL:
  4526. return &NumberLiteral{Val: lhs.Val * rhs.Val}
  4527. case DIV:
  4528. if rhs.Val == 0 {
  4529. return &NumberLiteral{Val: 0}
  4530. }
  4531. return &NumberLiteral{Val: lhs.Val / rhs.Val}
  4532. case MOD:
  4533. return &NumberLiteral{Val: math.Mod(lhs.Val, rhs.Val)}
  4534. case EQ:
  4535. return &BooleanLiteral{Val: lhs.Val == rhs.Val}
  4536. case NEQ:
  4537. return &BooleanLiteral{Val: lhs.Val != rhs.Val}
  4538. case GT:
  4539. return &BooleanLiteral{Val: lhs.Val > rhs.Val}
  4540. case GTE:
  4541. return &BooleanLiteral{Val: lhs.Val >= rhs.Val}
  4542. case LT:
  4543. return &BooleanLiteral{Val: lhs.Val < rhs.Val}
  4544. case LTE:
  4545. return &BooleanLiteral{Val: lhs.Val <= rhs.Val}
  4546. }
  4547. case *IntegerLiteral:
  4548. switch op {
  4549. case ADD:
  4550. return &NumberLiteral{Val: lhs.Val + float64(rhs.Val)}
  4551. case SUB:
  4552. return &NumberLiteral{Val: lhs.Val - float64(rhs.Val)}
  4553. case MUL:
  4554. return &NumberLiteral{Val: lhs.Val * float64(rhs.Val)}
  4555. case DIV:
  4556. if float64(rhs.Val) == 0 {
  4557. return &NumberLiteral{Val: 0}
  4558. }
  4559. return &NumberLiteral{Val: lhs.Val / float64(rhs.Val)}
  4560. case MOD:
  4561. return &NumberLiteral{Val: math.Mod(lhs.Val, float64(rhs.Val))}
  4562. case EQ:
  4563. return &BooleanLiteral{Val: lhs.Val == float64(rhs.Val)}
  4564. case NEQ:
  4565. return &BooleanLiteral{Val: lhs.Val != float64(rhs.Val)}
  4566. case GT:
  4567. return &BooleanLiteral{Val: lhs.Val > float64(rhs.Val)}
  4568. case GTE:
  4569. return &BooleanLiteral{Val: lhs.Val >= float64(rhs.Val)}
  4570. case LT:
  4571. return &BooleanLiteral{Val: lhs.Val < float64(rhs.Val)}
  4572. case LTE:
  4573. return &BooleanLiteral{Val: lhs.Val <= float64(rhs.Val)}
  4574. }
  4575. case *UnsignedLiteral:
  4576. return reduceBinaryExprNumberLHS(op, lhs, &NumberLiteral{Val: float64(rhs.Val)})
  4577. case *NilLiteral:
  4578. return &BooleanLiteral{Val: false}
  4579. }
  4580. return &BinaryExpr{Op: op, LHS: lhs, RHS: rhs}
  4581. }
  4582. func reduceBinaryExprStringLHS(op Token, lhs *StringLiteral, rhs Expr, loc *time.Location) Expr {
  4583. switch rhs := rhs.(type) {
  4584. case *StringLiteral:
  4585. switch op {
  4586. case EQ:
  4587. var expr Expr = &BooleanLiteral{Val: lhs.Val == rhs.Val}
  4588. // This might be a comparison between time literals.
  4589. // If it is, parse the time literals and then compare since it
  4590. // could be a different result if they use different formats
  4591. // for the same time.
  4592. if lhs.IsTimeLiteral() && rhs.IsTimeLiteral() {
  4593. tlhs, err := lhs.ToTimeLiteral(loc)
  4594. if err != nil {
  4595. return expr
  4596. }
  4597. trhs, err := rhs.ToTimeLiteral(loc)
  4598. if err != nil {
  4599. return expr
  4600. }
  4601. t := reduceBinaryExprTimeLHS(op, tlhs, trhs, loc)
  4602. if _, ok := t.(*BinaryExpr); !ok {
  4603. expr = t
  4604. }
  4605. }
  4606. return expr
  4607. case NEQ:
  4608. var expr Expr = &BooleanLiteral{Val: lhs.Val != rhs.Val}
  4609. // This might be a comparison between time literals.
  4610. // If it is, parse the time literals and then compare since it
  4611. // could be a different result if they use different formats
  4612. // for the same time.
  4613. if lhs.IsTimeLiteral() && rhs.IsTimeLiteral() {
  4614. tlhs, err := lhs.ToTimeLiteral(loc)
  4615. if err != nil {
  4616. return expr
  4617. }
  4618. trhs, err := rhs.ToTimeLiteral(loc)
  4619. if err != nil {
  4620. return expr
  4621. }
  4622. t := reduceBinaryExprTimeLHS(op, tlhs, trhs, loc)
  4623. if _, ok := t.(*BinaryExpr); !ok {
  4624. expr = t
  4625. }
  4626. }
  4627. return expr
  4628. case ADD:
  4629. return &StringLiteral{Val: lhs.Val + rhs.Val}
  4630. default:
  4631. // Attempt to convert the string literal to a time literal.
  4632. t, err := lhs.ToTimeLiteral(loc)
  4633. if err != nil {
  4634. break
  4635. }
  4636. expr := reduceBinaryExprTimeLHS(op, t, rhs, loc)
  4637. // If the returned expression is still a binary expr, that means
  4638. // we couldn't reduce it so this wasn't used in a time literal context.
  4639. if _, ok := expr.(*BinaryExpr); !ok {
  4640. return expr
  4641. }
  4642. }
  4643. case *DurationLiteral:
  4644. // Attempt to convert the string literal to a time literal.
  4645. t, err := lhs.ToTimeLiteral(loc)
  4646. if err != nil {
  4647. break
  4648. }
  4649. expr := reduceBinaryExprTimeLHS(op, t, rhs, loc)
  4650. // If the returned expression is still a binary expr, that means
  4651. // we couldn't reduce it so this wasn't used in a time literal context.
  4652. if _, ok := expr.(*BinaryExpr); !ok {
  4653. return expr
  4654. }
  4655. case *TimeLiteral:
  4656. // Attempt to convert the string literal to a time literal.
  4657. t, err := lhs.ToTimeLiteral(loc)
  4658. if err != nil {
  4659. break
  4660. }
  4661. expr := reduceBinaryExprTimeLHS(op, t, rhs, loc)
  4662. // If the returned expression is still a binary expr, that means
  4663. // we couldn't reduce it so this wasn't used in a time literal context.
  4664. if _, ok := expr.(*BinaryExpr); !ok {
  4665. return expr
  4666. }
  4667. case *IntegerLiteral:
  4668. // Attempt to convert the string literal to a time literal.
  4669. t, err := lhs.ToTimeLiteral(loc)
  4670. if err != nil {
  4671. break
  4672. }
  4673. expr := reduceBinaryExprTimeLHS(op, t, rhs, loc)
  4674. // If the returned expression is still a binary expr, that means
  4675. // we couldn't reduce it so this wasn't used in a time literal context.
  4676. if _, ok := expr.(*BinaryExpr); !ok {
  4677. return expr
  4678. }
  4679. case *NilLiteral:
  4680. switch op {
  4681. case EQ, NEQ:
  4682. return &BooleanLiteral{Val: false}
  4683. }
  4684. }
  4685. return &BinaryExpr{Op: op, LHS: lhs, RHS: rhs}
  4686. }
  4687. func reduceBinaryExprTimeLHS(op Token, lhs *TimeLiteral, rhs Expr, loc *time.Location) Expr {
  4688. switch rhs := rhs.(type) {
  4689. case *DurationLiteral:
  4690. switch op {
  4691. case ADD:
  4692. return &TimeLiteral{Val: lhs.Val.Add(rhs.Val)}
  4693. case SUB:
  4694. return &TimeLiteral{Val: lhs.Val.Add(-rhs.Val)}
  4695. }
  4696. case *IntegerLiteral:
  4697. d := &DurationLiteral{Val: time.Duration(rhs.Val)}
  4698. expr := reduceBinaryExprTimeLHS(op, lhs, d, loc)
  4699. if _, ok := expr.(*BinaryExpr); !ok {
  4700. return expr
  4701. }
  4702. case *TimeLiteral:
  4703. switch op {
  4704. case SUB:
  4705. return &DurationLiteral{Val: lhs.Val.Sub(rhs.Val)}
  4706. case EQ:
  4707. return &BooleanLiteral{Val: lhs.Val.Equal(rhs.Val)}
  4708. case NEQ:
  4709. return &BooleanLiteral{Val: !lhs.Val.Equal(rhs.Val)}
  4710. case GT:
  4711. return &BooleanLiteral{Val: lhs.Val.After(rhs.Val)}
  4712. case GTE:
  4713. return &BooleanLiteral{Val: lhs.Val.After(rhs.Val) || lhs.Val.Equal(rhs.Val)}
  4714. case LT:
  4715. return &BooleanLiteral{Val: lhs.Val.Before(rhs.Val)}
  4716. case LTE:
  4717. return &BooleanLiteral{Val: lhs.Val.Before(rhs.Val) || lhs.Val.Equal(rhs.Val)}
  4718. }
  4719. case *StringLiteral:
  4720. t, err := rhs.ToTimeLiteral(loc)
  4721. if err != nil {
  4722. break
  4723. }
  4724. expr := reduceBinaryExprTimeLHS(op, lhs, t, loc)
  4725. // If the returned expression is still a binary expr, that means
  4726. // we couldn't reduce it so this wasn't used in a time literal context.
  4727. if _, ok := expr.(*BinaryExpr); !ok {
  4728. return expr
  4729. }
  4730. case *NilLiteral:
  4731. return &BooleanLiteral{Val: false}
  4732. }
  4733. return &BinaryExpr{Op: op, LHS: lhs, RHS: rhs}
  4734. }
  4735. func reduceCall(expr *Call, valuer Valuer) Expr {
  4736. // Otherwise reduce arguments.
  4737. var args []Expr
  4738. literalsOnly := true
  4739. if len(expr.Args) > 0 {
  4740. args = make([]Expr, len(expr.Args))
  4741. for i, arg := range expr.Args {
  4742. args[i] = reduce(arg, valuer)
  4743. if !isLiteral(args[i]) {
  4744. literalsOnly = false
  4745. }
  4746. }
  4747. }
  4748. // Evaluate a function call if the valuer is a CallValuer and
  4749. // the arguments are only literals.
  4750. if literalsOnly {
  4751. if valuer, ok := valuer.(CallValuer); ok {
  4752. argVals := make([]interface{}, len(args))
  4753. for i := range args {
  4754. argVals[i] = Eval(args[i], nil)
  4755. }
  4756. if v, ok := valuer.Call(expr.Name, argVals); ok {
  4757. return asLiteral(v)
  4758. }
  4759. }
  4760. }
  4761. return &Call{Name: expr.Name, Args: args}
  4762. }
  4763. func reduceParenExpr(expr *ParenExpr, valuer Valuer) Expr {
  4764. subexpr := reduce(expr.Expr, valuer)
  4765. if subexpr, ok := subexpr.(*BinaryExpr); ok {
  4766. return &ParenExpr{Expr: subexpr}
  4767. }
  4768. return subexpr
  4769. }
  4770. func reduceVarRef(expr *VarRef, valuer Valuer) Expr {
  4771. // Ignore if there is no valuer.
  4772. if valuer == nil {
  4773. return &VarRef{Val: expr.Val, Type: expr.Type}
  4774. }
  4775. // Retrieve the value of the ref.
  4776. // Ignore if the value doesn't exist.
  4777. v, ok := valuer.Value(expr.Val)
  4778. if !ok {
  4779. return &VarRef{Val: expr.Val, Type: expr.Type}
  4780. }
  4781. // Return the value as a literal.
  4782. return asLiteral(v)
  4783. }
  4784. // asLiteral takes an interface and converts it into an influxql literal.
  4785. func asLiteral(v interface{}) Literal {
  4786. switch v := v.(type) {
  4787. case bool:
  4788. return &BooleanLiteral{Val: v}
  4789. case time.Duration:
  4790. return &DurationLiteral{Val: v}
  4791. case float64:
  4792. return &NumberLiteral{Val: v}
  4793. case int64:
  4794. return &IntegerLiteral{Val: v}
  4795. case string:
  4796. return &StringLiteral{Val: v}
  4797. case time.Time:
  4798. return &TimeLiteral{Val: v}
  4799. default:
  4800. return &NilLiteral{}
  4801. }
  4802. }
  4803. // isLiteral returns if the expression is a literal.
  4804. func isLiteral(expr Expr) bool {
  4805. _, ok := expr.(Literal)
  4806. return ok
  4807. }
  4808. // Valuer is the interface that wraps the Value() method.
  4809. type Valuer interface {
  4810. // Value returns the value and existence flag for a given key.
  4811. Value(key string) (interface{}, bool)
  4812. }
  4813. // CallValuer implements the Call method for evaluating function calls.
  4814. type CallValuer interface {
  4815. Valuer
  4816. // Call is invoked to evaluate a function call (if possible).
  4817. Call(name string, args []interface{}) (interface{}, bool)
  4818. }
  4819. // ZoneValuer is the interface that specifies the current time zone.
  4820. type ZoneValuer interface {
  4821. Valuer
  4822. // Zone returns the time zone location. This function may return nil
  4823. // if no time zone is known.
  4824. Zone() *time.Location
  4825. }
  4826. var _ CallValuer = (*NowValuer)(nil)
  4827. var _ ZoneValuer = (*NowValuer)(nil)
  4828. // NowValuer returns only the value for "now()".
  4829. type NowValuer struct {
  4830. Now time.Time
  4831. Location *time.Location
  4832. }
  4833. // Value is a method that returns the value and existence flag for a given key.
  4834. func (v *NowValuer) Value(key string) (interface{}, bool) {
  4835. if !v.Now.IsZero() && key == "now()" {
  4836. return v.Now, true
  4837. }
  4838. return nil, false
  4839. }
  4840. // Call evaluates the now() function to replace now() with the current time.
  4841. func (v *NowValuer) Call(name string, args []interface{}) (interface{}, bool) {
  4842. if name == "now" && len(args) == 0 {
  4843. return v.Now, true
  4844. }
  4845. return nil, false
  4846. }
  4847. // Zone is a method that returns the time.Location.
  4848. func (v *NowValuer) Zone() *time.Location {
  4849. if v.Location != nil {
  4850. return v.Location
  4851. }
  4852. return nil
  4853. }
  4854. // MultiValuer returns a Valuer that iterates over multiple Valuer instances
  4855. // to find a match.
  4856. func MultiValuer(valuers ...Valuer) Valuer {
  4857. return multiValuer(valuers)
  4858. }
  4859. type multiValuer []Valuer
  4860. var _ CallValuer = multiValuer(nil)
  4861. var _ ZoneValuer = multiValuer(nil)
  4862. func (a multiValuer) Value(key string) (interface{}, bool) {
  4863. for _, valuer := range a {
  4864. if v, ok := valuer.Value(key); ok {
  4865. return v, true
  4866. }
  4867. }
  4868. return nil, false
  4869. }
  4870. func (a multiValuer) Call(name string, args []interface{}) (interface{}, bool) {
  4871. for _, valuer := range a {
  4872. if valuer, ok := valuer.(CallValuer); ok {
  4873. if v, ok := valuer.Call(name, args); ok {
  4874. return v, true
  4875. }
  4876. }
  4877. }
  4878. return nil, false
  4879. }
  4880. func (a multiValuer) Zone() *time.Location {
  4881. for _, valuer := range a {
  4882. if valuer, ok := valuer.(ZoneValuer); ok {
  4883. if v := valuer.Zone(); v != nil {
  4884. return v
  4885. }
  4886. }
  4887. }
  4888. return nil
  4889. }
  4890. // ContainsVarRef returns true if expr is a VarRef or contains one.
  4891. func ContainsVarRef(expr Expr) bool {
  4892. var v containsVarRefVisitor
  4893. Walk(&v, expr)
  4894. return v.contains
  4895. }
  4896. type containsVarRefVisitor struct {
  4897. contains bool
  4898. }
  4899. func (v *containsVarRefVisitor) Visit(n Node) Visitor {
  4900. switch n.(type) {
  4901. case *Call:
  4902. return nil
  4903. case *VarRef:
  4904. v.contains = true
  4905. }
  4906. return v
  4907. }
  4908. func IsSelector(expr Expr) bool {
  4909. if call, ok := expr.(*Call); ok {
  4910. switch call.Name {
  4911. case "first", "last", "min", "max", "percentile", "sample", "top", "bottom":
  4912. return true
  4913. }
  4914. }
  4915. return false
  4916. }
  4917. // stringSetSlice returns a sorted slice of keys from a string set.
  4918. func stringSetSlice(m map[string]struct{}) []string {
  4919. if m == nil {
  4920. return nil
  4921. }
  4922. a := make([]string, 0, len(m))
  4923. for k := range m {
  4924. a = append(a, k)
  4925. }
  4926. sort.Strings(a)
  4927. return a
  4928. }
  4929. // TimeRange represents a range of time from Min to Max. The times are inclusive.
  4930. type TimeRange struct {
  4931. Min, Max time.Time
  4932. }
  4933. // Intersect joins this TimeRange with another TimeRange.
  4934. func (t TimeRange) Intersect(other TimeRange) TimeRange {
  4935. if !other.Min.IsZero() {
  4936. if t.Min.IsZero() || other.Min.After(t.Min) {
  4937. t.Min = other.Min
  4938. }
  4939. }
  4940. if !other.Max.IsZero() {
  4941. if t.Max.IsZero() || other.Max.Before(t.Max) {
  4942. t.Max = other.Max
  4943. }
  4944. }
  4945. return t
  4946. }
  4947. // IsZero is true if the min and max of the time range are zero.
  4948. func (t TimeRange) IsZero() bool {
  4949. return t.Min.IsZero() && t.Max.IsZero()
  4950. }
  4951. // Used by TimeRange methods.
  4952. var minTime = time.Unix(0, MinTime)
  4953. var maxTime = time.Unix(0, MaxTime)
  4954. // MinTime returns the minimum time of the TimeRange.
  4955. // If the minimum time is zero, this returns the minimum possible time.
  4956. func (t TimeRange) MinTime() time.Time {
  4957. if t.Min.IsZero() {
  4958. return minTime
  4959. }
  4960. return t.Min
  4961. }
  4962. // MaxTime returns the maximum time of the TimeRange.
  4963. // If the maximum time is zero, this returns the maximum possible time.
  4964. func (t TimeRange) MaxTime() time.Time {
  4965. if t.Max.IsZero() {
  4966. return maxTime
  4967. }
  4968. return t.Max
  4969. }
  4970. // MinTimeNano returns the minimum time in nanoseconds since the epoch.
  4971. // If the minimum time is zero, this returns the minimum possible time.
  4972. func (t TimeRange) MinTimeNano() int64 {
  4973. if t.Min.IsZero() {
  4974. return MinTime
  4975. }
  4976. return t.Min.UnixNano()
  4977. }
  4978. // MaxTimeNano returns the maximum time in nanoseconds since the epoch.
  4979. // If the maximum time is zero, this returns the maximum possible time.
  4980. func (t TimeRange) MaxTimeNano() int64 {
  4981. if t.Max.IsZero() {
  4982. return MaxTime
  4983. }
  4984. return t.Max.UnixNano()
  4985. }
  4986. // ConditionExpr extracts the time range and the condition from an expression.
  4987. // We only support simple time ranges that are constrained with AND and are not nested.
  4988. // This throws an error when we encounter a time condition that is combined with OR
  4989. // to prevent returning unexpected results that we do not support.
  4990. func ConditionExpr(cond Expr, valuer Valuer) (Expr, TimeRange, error) {
  4991. expr, tr, err := conditionExpr(cond, valuer)
  4992. // Remove top level parentheses
  4993. if e, ok := expr.(*ParenExpr); ok {
  4994. expr = e.Expr
  4995. }
  4996. if e, ok := expr.(*BooleanLiteral); ok && e.Val {
  4997. // If the condition is true, return nil instead to indicate there
  4998. // is no condition.
  4999. expr = nil
  5000. }
  5001. return expr, tr, err
  5002. }
  5003. func conditionExpr(cond Expr, valuer Valuer) (Expr, TimeRange, error) {
  5004. if cond == nil {
  5005. return nil, TimeRange{}, nil
  5006. }
  5007. switch cond := cond.(type) {
  5008. case *BinaryExpr:
  5009. if cond.Op == AND || cond.Op == OR {
  5010. lhsExpr, lhsTime, err := conditionExpr(cond.LHS, valuer)
  5011. if err != nil {
  5012. return nil, TimeRange{}, err
  5013. }
  5014. rhsExpr, rhsTime, err := conditionExpr(cond.RHS, valuer)
  5015. if err != nil {
  5016. return nil, TimeRange{}, err
  5017. }
  5018. // Always intersect the time range even if it makes no sense.
  5019. // There is no such thing as using OR with a time range.
  5020. timeRange := lhsTime.Intersect(rhsTime)
  5021. // Combine the left and right expression.
  5022. if rhsExpr == nil {
  5023. return lhsExpr, timeRange, nil
  5024. } else if lhsExpr == nil {
  5025. return rhsExpr, timeRange, nil
  5026. }
  5027. return reduce(&BinaryExpr{
  5028. Op: cond.Op,
  5029. LHS: lhsExpr,
  5030. RHS: rhsExpr,
  5031. }, nil), timeRange, nil
  5032. }
  5033. // If either the left or the right side is "time", we are looking at
  5034. // a time range.
  5035. if lhs, ok := cond.LHS.(*VarRef); ok && strings.ToLower(lhs.Val) == "time" {
  5036. timeRange, err := getTimeRange(cond.Op, cond.RHS, valuer)
  5037. return nil, timeRange, err
  5038. } else if rhs, ok := cond.RHS.(*VarRef); ok && strings.ToLower(rhs.Val) == "time" {
  5039. // Swap the op for the opposite if it is a comparison.
  5040. op := cond.Op
  5041. switch op {
  5042. case GT:
  5043. op = LT
  5044. case LT:
  5045. op = GT
  5046. case GTE:
  5047. op = LTE
  5048. case LTE:
  5049. op = GTE
  5050. }
  5051. timeRange, err := getTimeRange(op, cond.LHS, valuer)
  5052. return nil, timeRange, err
  5053. }
  5054. return reduce(cond, valuer), TimeRange{}, nil
  5055. case *ParenExpr:
  5056. expr, timeRange, err := conditionExpr(cond.Expr, valuer)
  5057. if err != nil {
  5058. return nil, TimeRange{}, err
  5059. } else if expr == nil {
  5060. return nil, timeRange, nil
  5061. }
  5062. return reduce(&ParenExpr{Expr: expr}, nil), timeRange, nil
  5063. case *BooleanLiteral:
  5064. return cond, TimeRange{}, nil
  5065. default:
  5066. return nil, TimeRange{}, fmt.Errorf("invalid condition expression: %s", cond)
  5067. }
  5068. }
  5069. // getTimeRange returns the time range associated with this comparison.
  5070. // op is the operation that is used for comparison and rhs is the right hand side
  5071. // of the expression. The left hand side is always assumed to be "time".
  5072. func getTimeRange(op Token, rhs Expr, valuer Valuer) (TimeRange, error) {
  5073. // If literal looks like a date time then parse it as a time literal.
  5074. if strlit, ok := rhs.(*StringLiteral); ok {
  5075. if strlit.IsTimeLiteral() {
  5076. var loc *time.Location
  5077. if valuer, ok := valuer.(ZoneValuer); ok {
  5078. loc = valuer.Zone()
  5079. }
  5080. t, err := strlit.ToTimeLiteral(loc)
  5081. if err != nil {
  5082. return TimeRange{}, err
  5083. }
  5084. rhs = t
  5085. }
  5086. }
  5087. // Evaluate the RHS to replace "now()" with the current time.
  5088. rhs = Reduce(rhs, valuer)
  5089. var value time.Time
  5090. switch lit := rhs.(type) {
  5091. case *TimeLiteral:
  5092. if lit.Val.After(time.Unix(0, MaxTime)) {
  5093. return TimeRange{}, fmt.Errorf("time %s overflows time literal", lit.Val.Format(time.RFC3339))
  5094. } else if lit.Val.Before(time.Unix(0, MinTime+1)) {
  5095. // The minimum allowable time literal is one greater than the minimum time because the minimum time
  5096. // is a sentinel value only used internally.
  5097. return TimeRange{}, fmt.Errorf("time %s underflows time literal", lit.Val.Format(time.RFC3339))
  5098. }
  5099. value = lit.Val
  5100. case *DurationLiteral:
  5101. value = time.Unix(0, int64(lit.Val)).UTC()
  5102. case *NumberLiteral:
  5103. value = time.Unix(0, int64(lit.Val)).UTC()
  5104. case *IntegerLiteral:
  5105. value = time.Unix(0, lit.Val).UTC()
  5106. default:
  5107. return TimeRange{}, fmt.Errorf("invalid operation: time and %T are not compatible", lit)
  5108. }
  5109. timeRange := TimeRange{}
  5110. switch op {
  5111. case GT:
  5112. timeRange.Min = value.Add(time.Nanosecond)
  5113. case GTE:
  5114. timeRange.Min = value
  5115. case LT:
  5116. timeRange.Max = value.Add(-time.Nanosecond)
  5117. case LTE:
  5118. timeRange.Max = value
  5119. case EQ:
  5120. timeRange.Min, timeRange.Max = value, value
  5121. default:
  5122. return TimeRange{}, fmt.Errorf("invalid time comparison operator: %s", op)
  5123. }
  5124. return timeRange, nil
  5125. }