executor.go 220 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121
  1. package executor
  2. import (
  3. "container/heap"
  4. "encoding/hex"
  5. "errors"
  6. "fmt"
  7. "math/rand"
  8. "sort"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "github.com/danfragoso/pizzasql-next/pkg/analyzer"
  13. "github.com/danfragoso/pizzasql-next/pkg/lexer"
  14. "github.com/danfragoso/pizzasql-next/pkg/parser"
  15. "github.com/danfragoso/pizzasql-next/pkg/pgerror"
  16. "github.com/danfragoso/pizzasql-next/pkg/storage"
  17. "github.com/danfragoso/pizzasql-next/pkg/version"
  18. )
  19. // ErrUnsupportedFeature marks DDL that PizzaSQL intentionally rejects instead
  20. // of silently accepting with different semantics. Protocol layers map it to a
  21. // feature-not-supported SQLSTATE rather than a generic internal error.
  22. var ErrUnsupportedFeature = errors.New("unsupported feature")
  23. // ErrNoTransaction marks a transaction-control statement that found no
  24. // transaction to act on. Adapters may report it as a benign no-op (PostgreSQL
  25. // treats ROLLBACK outside a transaction as a warning) instead of an internal
  26. // error.
  27. var ErrNoTransaction = errors.New("no transaction in progress")
  28. // Executor executes SQL statements.
  29. type Executor struct {
  30. schema *storage.SchemaManager
  31. table *storage.TableManager
  32. session *storage.Session
  33. analyzer *analyzer.Analyzer
  34. catalog *analyzer.Catalog
  35. // Last SchemaManager version reflected in catalog.
  36. catalogVersion uint64
  37. // Multi-database support
  38. attachedDatabases map[string]*DatabaseConnection // alias -> connection
  39. currentDatabase string // current database alias (default is "main")
  40. // Transaction state
  41. inTransaction bool
  42. savepoints []string // stack of savepoint names
  43. savepointStates []*storage.SessionSavepoint // full session state (rows and staged DDL) per savepoint
  44. // LISTEN/NOTIFY state. The hub and subscriber are per database instance;
  45. // listenOps and notifyQueue are staged until COMMIT so LISTEN and NOTIFY
  46. // observe transactional visibility.
  47. hub *storage.Hub
  48. subscriber *storage.Subscriber
  49. backendPID int32
  50. listens map[string]bool
  51. listenOps []listenOp
  52. notifyQueue []storage.Notification
  53. notificationSaves []notificationSnapshot
  54. // Subquery context for correlated subqueries
  55. outerRow storage.Row
  56. // Per-query cache for non-correlated IN (SELECT ...) subquery results.
  57. // Keyed by subquery AST pointer; valid for one top-level Execute call.
  58. subqueryCache map[*parser.SelectStmt]*Result
  59. // Per-query cache for decorrelated scalar aggregate subqueries.
  60. // Keyed by subquery AST pointer; valid for one top-level Execute call.
  61. correlatedAggCache map[*parser.SelectStmt]*correlatedAggCache
  62. // Per-query cache of parsed array literals, keyed by the array expression's
  63. // AST pointer. The evaluated text is compared before a hit is used so a
  64. // value that changes between rows or executions is re-parsed.
  65. arrayCache map[parser.Expr]*arrayParseEntry
  66. // Per-query cache of evaluated constant array operands, keyed by AST
  67. // pointer. It keeps `= ANY($1)` from rebuilding the same canonical array
  68. // text for every row of a scan.
  69. arrayValueCache map[parser.Expr]interface{}
  70. // typeScopes holds the column-type resolvers of the SELECT statements being
  71. // evaluated, innermost last. Value-time consumers (array subscripts) use
  72. // them to recover a column's declared type.
  73. typeScopes []columnTypeResolver
  74. // In-memory view registry: view name (lowercase) → SELECT AST.
  75. views map[string]*parser.SelectStmt
  76. // Materialized common table expressions for the current query, keyed by
  77. // lowercased CTE name. Recursive CTEs populate this during fixpoint
  78. // iteration so their own legs can read the working set.
  79. cteTables map[string]*cteTable
  80. // Session-local SQLite compatibility state, tracked per connection so
  81. // last_insert_rowid()/changes()/total_changes() reflect this session only.
  82. lastInsertRowID int64 // rowid of the most recent successful INSERT
  83. changes int64 // rows changed by the most recent INSERT/UPDATE/DELETE
  84. totalChanges int64 // rows changed since this connection opened (monotonic)
  85. // clock supplies the time for non-constant DEFAULT evaluation. Nil means
  86. // time.Now; tests inject it to observe per-statement evaluation without
  87. // depending on the wall clock.
  88. clock func() time.Time
  89. }
  90. type correlatedAggCache struct {
  91. values map[string]interface{}
  92. defaultValue interface{}
  93. }
  94. type correlatedAggSpec struct {
  95. innerKey parser.Expr
  96. outerKey *parser.ColumnRef
  97. aggExpr parser.Expr
  98. }
  99. // DatabaseConnection represents an attached database.
  100. type DatabaseConnection struct {
  101. Alias string
  102. Path string // Database path or identifier
  103. Schema *storage.SchemaManager
  104. Table *storage.TableManager
  105. }
  106. // New creates a new executor.
  107. func New(schema *storage.SchemaManager, table *storage.TableManager) *Executor {
  108. catalog := analyzer.NewCatalog()
  109. executor := &Executor{
  110. schema: schema,
  111. table: table,
  112. session: storage.NewSession(schema, table),
  113. analyzer: analyzer.New(catalog),
  114. catalog: catalog,
  115. attachedDatabases: make(map[string]*DatabaseConnection),
  116. currentDatabase: "main",
  117. views: make(map[string]*parser.SelectStmt),
  118. listens: make(map[string]bool),
  119. }
  120. // Expression indexes and CHECK predicates persist only SQL text, so the
  121. // storage layer needs a stateless evaluator to compute their values. The
  122. // evaluator is a package function with no per-connection state, so
  123. // registering it here is idempotent and safe across concurrent executors.
  124. table.SetExpressionEvaluator(EvalStoredExpression)
  125. // Non-constant DEFAULT expressions are likewise stored as SQL text; storage
  126. // evaluates them when it backfills ADD COLUMN rows or completes a row image
  127. // that predates the column. Storage samples the clock once per ALTER
  128. // statement through this executor, so the session clock also drives
  129. // storage-side evaluation; ordinary writes evaluate defaults once per
  130. // statement in this package.
  131. schema.SetDefaultEvaluator(evalDefaultExpressionAt)
  132. schema.SetDefaultClock(executor.statementNow)
  133. schema.SetCheckEvaluator(EvalCheckExpression)
  134. // Register the main database
  135. executor.attachedDatabases["main"] = &DatabaseConnection{
  136. Alias: "main",
  137. Path: schema.GetDatabaseName(),
  138. Schema: schema,
  139. Table: table,
  140. }
  141. return executor
  142. }
  143. // An Executor owns mutable session state and must not be used concurrently.
  144. // Use one executor per PostgreSQL connection or HTTP transaction/request.
  145. // NewSessionExecutor returns a new executor sharing the same schema and table
  146. // managers but with fresh per-executor state (transaction, subquery caches,
  147. // views). It is used to isolate concurrent requests that must not share mutable
  148. // executor state.
  149. func (e *Executor) NewSessionExecutor() *Executor {
  150. exec := New(e.schema, e.table)
  151. exec.SyncCatalog()
  152. return exec
  153. }
  154. // Session exposes the executor's catalog and row session. Protocol layers that
  155. // emulate system catalogs must read through it so their introspection observes
  156. // DDL staged by an open transaction, exactly like the SQL executor does.
  157. func (e *Executor) Session() *storage.Session {
  158. return e.session
  159. }
  160. // SyncCatalog synchronizes the analyzer catalog with the storage schema.
  161. func (e *Executor) SyncCatalog() error {
  162. tables, err := e.session.ListTables()
  163. if err != nil {
  164. return err
  165. }
  166. storageTables := make(map[string]struct{}, len(tables))
  167. for _, tableName := range tables {
  168. storageTables[strings.ToUpper(tableName)] = struct{}{}
  169. schema, err := e.session.GetSchema(tableName)
  170. if err != nil {
  171. continue
  172. }
  173. // Drop table from catalog if it exists, then recreate with updated schema
  174. e.catalog.DropTable(tableName)
  175. e.catalog.CreateTable(schema.ToAnalyzerTableInfo())
  176. }
  177. for _, table := range e.catalog.GetTables() {
  178. if table.IsView {
  179. continue
  180. }
  181. if _, exists := storageTables[strings.ToUpper(table.Name)]; !exists {
  182. e.catalog.DropTable(table.Name)
  183. }
  184. }
  185. e.catalogVersion = e.session.Version()
  186. return nil
  187. }
  188. // Execute executes a SQL statement.
  189. func (e *Executor) Execute(stmt parser.Statement) (*Result, error) {
  190. if _, beginning := stmt.(*parser.BeginStmt); !beginning && !e.inTransaction {
  191. e.schema.LockStatement()
  192. defer e.schema.UnlockStatement()
  193. }
  194. e.subqueryCache = make(map[*parser.SelectStmt]*Result)
  195. e.correlatedAggCache = make(map[*parser.SelectStmt]*correlatedAggCache)
  196. e.arrayCache = make(map[parser.Expr]*arrayParseEntry)
  197. e.arrayValueCache = make(map[parser.Expr]interface{})
  198. defer func() {
  199. e.subqueryCache = nil
  200. e.correlatedAggCache = nil
  201. e.arrayCache = nil
  202. e.arrayValueCache = nil
  203. }()
  204. // PRAGMA doesn't need analysis. SQLite catalog-introspection pragmas
  205. // (index_list, index_info, table_xinfo) are answered by the catalog agent
  206. // first; everything else falls through to the built-in handler.
  207. if pragma, ok := stmt.(*parser.PragmaStmt); ok {
  208. if res, handled, err := e.sqliteCatalogPragma(pragma); handled {
  209. return res, err
  210. }
  211. return e.executePragma(pragma)
  212. }
  213. // EXPLAIN doesn't need analysis
  214. if explain, ok := stmt.(*parser.ExplainStmt); ok {
  215. return e.executeExplain(explain)
  216. }
  217. // Transaction statements don't need analysis
  218. switch s := stmt.(type) {
  219. case *parser.BeginStmt:
  220. return e.executeBegin(s)
  221. case *parser.CommitStmt:
  222. return e.executeCommit(s)
  223. case *parser.RollbackStmt:
  224. return e.executeRollback(s)
  225. case *parser.SavepointStmt:
  226. return e.executeSavepoint(s)
  227. case *parser.ReleaseStmt:
  228. return e.executeRelease(s)
  229. case *parser.CreateIndexStmt:
  230. return e.executeCreateIndex(s)
  231. case *parser.DropIndexStmt:
  232. return e.executeDropIndex(s)
  233. case *parser.CreateViewStmt:
  234. return e.executeCreateView(s)
  235. case *parser.DropViewStmt:
  236. return e.executeDropView(s)
  237. case *parser.AttachStmt:
  238. return e.executeAttach(s)
  239. case *parser.DetachStmt:
  240. return e.executeDetach(s)
  241. case *parser.AnalyzeStmt:
  242. return e.executeAnalyze(s)
  243. case *parser.ListenStmt:
  244. return e.executeListen(s)
  245. case *parser.UnlistenStmt:
  246. return e.executeUnlisten(s)
  247. case *parser.NotifyStmt:
  248. return e.executeNotify(s)
  249. }
  250. // SQLite catalog/metadata dispatch. SELECTs against sqlite_master /
  251. // sqlite_schema must be answered before the analyzer, which would otherwise
  252. // reject those virtual tables as unknown. Falls through when unhandled.
  253. if sel, ok := stmt.(*parser.SelectStmt); ok {
  254. if res, handled, err := e.sqliteCatalogSelect(sel); handled {
  255. return res, err
  256. }
  257. }
  258. // Analyze first. If the cached analyzer catalog is stale because schema was
  259. // changed through another executor/API path, resync from storage and retry
  260. // once before returning table/column-not-found errors.
  261. if err := e.analyzeWithCatalogRetry(stmt); err != nil {
  262. return nil, err
  263. }
  264. switch s := stmt.(type) {
  265. case *parser.SelectStmt:
  266. return e.executeSelect(s)
  267. case *parser.InsertStmt:
  268. if len(s.Returning) == 0 {
  269. return e.executeInsert(s)
  270. }
  271. return e.executeAtomicMutation(func() (*Result, error) { return e.executeInsert(s) })
  272. case *parser.UpdateStmt:
  273. if len(s.Returning) == 0 && e.isPointMutation(s.Table.Name, s.Where, s.Set) {
  274. return e.executeUpdate(s)
  275. }
  276. return e.executeAtomicMutation(func() (*Result, error) { return e.executeUpdate(s) })
  277. case *parser.DeleteStmt:
  278. if len(s.Returning) == 0 && e.isPointMutation(s.Table.Name, s.Where, nil) {
  279. return e.executeDelete(s)
  280. }
  281. return e.executeAtomicMutation(func() (*Result, error) { return e.executeDelete(s) })
  282. case *parser.CreateTableStmt:
  283. return e.executeDDL(func() (*Result, error) { return e.executeCreateTable(s) })
  284. case *parser.DropTableStmt:
  285. return e.executeDDL(func() (*Result, error) { return e.executeDropTable(s) })
  286. case *parser.CreateIndexStmt:
  287. return e.executeDDL(func() (*Result, error) { return e.executeCreateIndex(s) })
  288. case *parser.DropIndexStmt:
  289. return e.executeDDL(func() (*Result, error) { return e.executeDropIndex(s) })
  290. case *parser.AlterTableStmt:
  291. return e.executeDDL(func() (*Result, error) { return e.executeAlterTable(s) })
  292. default:
  293. return nil, fmt.Errorf("unsupported statement type: %T", stmt)
  294. }
  295. }
  296. // executeDDL runs a schema-changing statement with a statement savepoint. A
  297. // failing DDL statement discards every catalog and row effect it staged and
  298. // leaves the transaction's prior schema intact, whether or not a transaction is
  299. // open.
  300. func (e *Executor) executeDDL(apply func() (*Result, error)) (*Result, error) {
  301. if !e.session.InTx() {
  302. return apply()
  303. }
  304. savepoint := e.session.Savepoint()
  305. result, err := apply()
  306. if err != nil {
  307. e.session.RollbackToSavepoint(savepoint)
  308. _ = e.SyncCatalog()
  309. }
  310. return result, err
  311. }
  312. func (e *Executor) analyzeWithCatalogRetry(stmt parser.Statement) error {
  313. if e.catalogVersion != e.session.Version() {
  314. if err := e.SyncCatalog(); err != nil {
  315. return err
  316. }
  317. }
  318. a := analyzer.New(e.catalog)
  319. err := a.Analyze(stmt)
  320. if err == nil {
  321. return nil
  322. }
  323. if !isCatalogMiss(err) {
  324. return err
  325. }
  326. if syncErr := e.SyncCatalog(); syncErr != nil {
  327. return err
  328. }
  329. a = analyzer.New(e.catalog)
  330. return a.Analyze(stmt)
  331. }
  332. func isCatalogMiss(err error) bool {
  333. var analysisErr *analyzer.AnalysisError
  334. if !errors.As(err, &analysisErr) {
  335. return false
  336. }
  337. return analysisErr.Type == analyzer.ErrTableNotFound ||
  338. analysisErr.Type == analyzer.ErrColumnNotFound
  339. }
  340. // isCountStarSingleTable reports whether the statement is the safe COUNT(*)
  341. // shape eligible for the metadata fast path: a single-table SELECT with exactly
  342. // one COUNT(*) column and no filters, grouping, DISTINCT, JOIN, subquery, or
  343. // LIMIT/OFFSET. Anything else returns false so unsupported shapes use the
  344. // normal scan path.
  345. func isCountStarSingleTable(stmt *parser.SelectStmt) bool {
  346. if stmt.Compound != nil || stmt.Distinct {
  347. return false
  348. }
  349. if stmt.Where != nil || stmt.Having != nil {
  350. return false
  351. }
  352. if len(stmt.GroupBy) > 0 || len(stmt.OrderBy) > 0 {
  353. return false
  354. }
  355. if stmt.Limit != nil || stmt.Offset != nil {
  356. return false
  357. }
  358. if len(stmt.From) != 1 {
  359. return false
  360. }
  361. ref := stmt.From[0]
  362. if ref.Subquery != nil || ref.Join != nil || ref.Function != nil {
  363. return false
  364. }
  365. if len(stmt.Columns) != 1 || stmt.Columns[0].Star {
  366. return false
  367. }
  368. fn, ok := stmt.Columns[0].Expr.(*parser.FunctionCall)
  369. if !ok {
  370. return false
  371. }
  372. if !strings.EqualFold(fn.Name, "count") || !fn.Star || len(fn.Args) > 0 {
  373. return false
  374. }
  375. return true
  376. }
  377. // executeSelect executes a SELECT statement (or compound SELECT).
  378. func (e *Executor) executeSelect(stmt *parser.SelectStmt) (*Result, error) {
  379. e.pushTypeScope(e.snapshotTypeResolver(stmt.From))
  380. defer e.popTypeScope()
  381. if len(stmt.With) > 0 {
  382. return e.executeWith(stmt)
  383. }
  384. if stmt.Compound != nil {
  385. return e.executeCompound(stmt.Compound)
  386. }
  387. if len(stmt.From) == 0 {
  388. // SELECT without FROM (e.g., SELECT 1+1)
  389. return e.executeSelectExpr(stmt)
  390. }
  391. if stmt.From[0].Function != nil {
  392. return e.executeSelectFromTableFunction(stmt)
  393. }
  394. // Non-recursive CTEs are desugared to derived tables by the parser. Preserve
  395. // every entry in a comma-separated list instead of dispatching solely on the
  396. // first derived table.
  397. if len(stmt.From) > 1 {
  398. allSubqueries := true
  399. for _, ref := range stmt.From {
  400. if ref.Subquery == nil || ref.Join != nil {
  401. allSubqueries = false
  402. break
  403. }
  404. }
  405. if allSubqueries {
  406. return e.executeSelectFromSubqueries(stmt)
  407. }
  408. }
  409. // Check if FROM clause is a subquery (derived table)
  410. if stmt.From[0].Subquery != nil {
  411. return e.executeSelectFromSubquery(stmt)
  412. }
  413. tableName := stmt.From[0].Name
  414. // A comma-separated list of materialized CTEs is an implicit cross join.
  415. // Handle it before the single-CTE shortcut below so later FROM entries are
  416. // not silently discarded.
  417. if len(stmt.From) > 1 {
  418. allCTEs := true
  419. for _, ref := range stmt.From {
  420. if ref.Subquery != nil || ref.Join != nil || !e.cteTableExists(ref.Name) {
  421. allCTEs = false
  422. break
  423. }
  424. }
  425. if allCTEs {
  426. return e.executeSelectOnMaterializedCTEs(stmt)
  427. }
  428. }
  429. // A materialized CTE is served from memory, not from storage.
  430. if cte, ok := e.cteTableFor(tableName); ok {
  431. return e.executeSelectOnMaterialized(stmt, cte.columns, cteRowsToValues(cte))
  432. }
  433. // Transparently expand view references as derived-table subqueries.
  434. if viewDef, ok := e.views[strings.ToLower(tableName)]; ok {
  435. alias := stmt.From[0].Alias
  436. if alias == "" {
  437. alias = tableName
  438. }
  439. modifiedStmt := *stmt
  440. modifiedFrom := make([]parser.TableRef, len(stmt.From))
  441. copy(modifiedFrom, stmt.From)
  442. modifiedFrom[0] = parser.TableRef{Subquery: viewDef, Alias: alias}
  443. modifiedStmt.From = modifiedFrom
  444. return e.executeSelectFromSubquery(&modifiedStmt)
  445. }
  446. schema, err := e.session.GetSchema(tableName)
  447. if err != nil {
  448. return nil, err
  449. }
  450. // COUNT(*) fast path: exact metadata-based count for the safe single-table
  451. // shape with no filters/grouping/distinct/join. Any unsupported shape falls
  452. // through to the normal scan path.
  453. if isCountStarSingleTable(stmt) {
  454. count, err := e.session.CountFast(tableName)
  455. if err != nil {
  456. return nil, err
  457. }
  458. result := NewResult("SELECT")
  459. if stmt.Columns[0].Alias != "" {
  460. result.AddColumn(stmt.Columns[0].Alias)
  461. } else {
  462. result.AddColumn("column1")
  463. }
  464. result.ColumnTypes = []string{inferExprType(stmt.Columns[0].Expr, nil)}
  465. result.AddRow(int64(count))
  466. return result, nil
  467. }
  468. // Multi-table FROM (comma-separated implicit cross join): collect and cross join all tables,
  469. // then apply WHERE after. Don't push WHERE down here — conditions reference multiple tables.
  470. isMultiTable := len(stmt.From) > 1 && stmt.From[0].Join == nil
  471. // Optimize constant WHERE clauses
  472. var constantWhereResult *bool
  473. if stmt.Where != nil && !isMultiTable {
  474. // Check if WHERE clause is a constant expression (doesn't reference any columns)
  475. refs := collectColumnRefs(stmt.Where)
  476. if len(refs) == 0 {
  477. // Evaluate the constant expression
  478. val, err := e.evalExpr(stmt.Where, nil)
  479. if err == nil {
  480. result := toBool(val)
  481. constantWhereResult = &result
  482. }
  483. }
  484. }
  485. // If WHERE is constant false, check if we have aggregates first
  486. if constantWhereResult != nil && !*constantWhereResult {
  487. // If query has GROUP BY, return empty result (no groups match)
  488. // If query has aggregates but no GROUP BY, evaluate them on empty row set
  489. if e.hasAggregates(stmt.Columns) {
  490. if len(stmt.GroupBy) > 0 {
  491. // GROUP BY with no matching rows: return empty result (no groups)
  492. // Fall through to the non-aggregate case below
  493. } else {
  494. // Aggregate without GROUP BY: return single row with aggregate results on empty set
  495. return e.executeAggregateSelect(stmt, []storage.Row{}, schema)
  496. }
  497. }
  498. // Non-aggregate query with WHERE false: return empty result using the
  499. // same wildcard expansion and type metadata the scanned path reports.
  500. refs := collectAllTableRefs(stmt.From)
  501. tableStars, starErr := e.resolveTableStars(stmt.From, stmt.Columns)
  502. if starErr != nil {
  503. return nil, starErr
  504. }
  505. result := NewResult("SELECT")
  506. for _, name := range e.selectColumnNames(stmt, schema, refs, isMultiTable, tableStars) {
  507. result.AddColumn(name)
  508. }
  509. if isMultiTable || stmt.From[0].Join != nil {
  510. result.ColumnTypes = e.joinedSelectColumnTypes(stmt, refs)
  511. } else {
  512. result.ColumnTypes = selectColumnTypes(stmt, schema)
  513. }
  514. return result, nil
  515. }
  516. // Try to use index for WHERE clause (single-table only)
  517. var rows []storage.Row
  518. usedIndex := false
  519. // If WHERE is constant true, skip it during table scan
  520. effectiveWhere := stmt.Where
  521. if constantWhereResult != nil && *constantWhereResult {
  522. effectiveWhere = nil
  523. }
  524. // Pre-evaluate non-correlated subqueries in the WHERE before the scan takes
  525. // the session lock.
  526. e.primeSubqueries(effectiveWhere)
  527. // A WHERE that contains a subquery is evaluated after the scan. Evaluating a
  528. // correlated subquery inside the locked scan re-enters the session lock and
  529. // deadlocks, so only a subquery-free predicate is pushed into the scan.
  530. whereHasSubquery := false
  531. for _, ref := range collectColumnRefs(effectiveWhere) {
  532. if ref == "__subquery__" {
  533. whereHasSubquery = true
  534. break
  535. }
  536. }
  537. canFilterInScan := effectiveWhere != nil && !whereHasSubquery && stmt.From[0].Alias == "" && !isMultiTable && stmt.From[0].Join == nil
  538. appliedInScan := false
  539. // A lookup may only restrict a correctly bound, preserved table. The
  540. // original predicate is still evaluated after the lookup/join.
  541. if effectiveWhere != nil && !isMultiTable {
  542. for _, condition := range splitANDClauses(effectiveWhere) {
  543. colName, colValue, isEquality := e.extractSelectLookupCondition(condition, stmt.From[0])
  544. if isEquality {
  545. if schema.IsSingleColumnPrimaryKey() && strings.EqualFold(schema.PrimaryKey, colName) && safePrimaryKeyLiteral(colValue) {
  546. row, getErr := e.session.GetByPK(tableName, fmt.Sprintf("%v", colValue))
  547. if getErr == nil {
  548. normalizeRowBySchema(row, schema)
  549. rows = []storage.Row{row}
  550. usedIndex = true
  551. } else if getErr == storage.ErrKeyNotFound {
  552. rows = []storage.Row{}
  553. usedIndex = true
  554. } else {
  555. return nil, getErr
  556. }
  557. } else {
  558. // Look for an index on this column
  559. indexes, _ := e.session.ListTableIndexes(tableName)
  560. for _, idx := range indexes {
  561. if len(idx.Columns) == 1 && strings.EqualFold(idx.Columns[0].Name, colName) {
  562. rows, err = e.session.SelectByIndex(tableName, idx.Name, colValue)
  563. if err == nil {
  564. usedIndex = true
  565. for i := range rows {
  566. normalizeRowBySchema(rows[i], schema)
  567. }
  568. }
  569. break
  570. }
  571. }
  572. }
  573. }
  574. if usedIndex {
  575. break
  576. }
  577. }
  578. }
  579. // Fall back to full table scan if no index used
  580. if !usedIndex {
  581. var filterErr error
  582. var filter func(storage.Row) bool
  583. if canFilterInScan {
  584. appliedInScan = true
  585. filter = func(row storage.Row) bool {
  586. val, ferr := e.evalExpr(effectiveWhere, row)
  587. if ferr != nil {
  588. filterErr = ferr
  589. return false
  590. }
  591. return toBool(val)
  592. }
  593. }
  594. if limit, bounded := scanLimit(stmt); bounded && (effectiveWhere == nil || canFilterInScan) {
  595. rows, err = e.session.SelectLimited(tableName, filter, limit)
  596. } else {
  597. rows, err = e.session.Select(tableName, filter)
  598. }
  599. if filterErr != nil {
  600. return nil, filterErr
  601. }
  602. for _, row := range rows {
  603. normalizeRowBySchema(row, schema)
  604. }
  605. }
  606. if err != nil {
  607. return nil, err
  608. }
  609. // Add table alias to rows if there's an explicit alias
  610. if stmt.From[0].Alias != "" {
  611. for i := range rows {
  612. rows[i] = e.addTableAlias(rows[i], stmt.From[0].Alias)
  613. }
  614. } else if isMultiTable {
  615. // For multi-table cross joins without alias, prefix columns with table name
  616. // so WHERE can distinguish t3.a3 from t7.a7.
  617. for i := range rows {
  618. rows[i] = e.addTableAlias(rows[i], tableName)
  619. }
  620. }
  621. // Apply WHERE for a single-table scan that did not push the predicate into
  622. // the locked scan (aliased tables, or a WHERE containing a subquery). A
  623. // query with a JOIN defers WHERE until after the join, because the WHERE may
  624. // reference columns from the joined table.
  625. if effectiveWhere != nil && !isMultiTable && stmt.From[0].Join == nil && !appliedInScan {
  626. var filterErr error
  627. var filtered []storage.Row
  628. for _, row := range rows {
  629. val, ferr := e.evalExpr(effectiveWhere, row)
  630. if ferr != nil {
  631. filterErr = ferr
  632. break
  633. }
  634. if toBool(val) {
  635. filtered = append(filtered, row)
  636. }
  637. }
  638. if filterErr != nil {
  639. return nil, filterErr
  640. }
  641. rows = filtered
  642. }
  643. // Handle explicit JOINs from the first FROM entry (single-table+JOIN path)
  644. if !isMultiTable && len(stmt.From) > 0 && stmt.From[0].Join != nil {
  645. rows, err = e.executeJoins(stmt.From[0], rows)
  646. if err != nil {
  647. return nil, err
  648. }
  649. // Cross-join with any remaining comma-separated FROM entries (mixed JOIN+comma syntax)
  650. for _, tref := range stmt.From[1:] {
  651. rightRows, rerr := e.session.Select(tref.Name, nil)
  652. if rerr != nil {
  653. return nil, rerr
  654. }
  655. rightAlias := tref.Alias
  656. if rightAlias == "" {
  657. rightAlias = tref.Name
  658. }
  659. for i := range rightRows {
  660. rightRows[i] = e.addTableAlias(rightRows[i], rightAlias)
  661. }
  662. var joined []storage.Row
  663. for _, l := range rows {
  664. for _, r := range rightRows {
  665. m := make(storage.Row, len(l)+len(r))
  666. for k, v := range l {
  667. m[k] = v
  668. }
  669. for k, v := range r {
  670. m[k] = v
  671. }
  672. joined = append(joined, m)
  673. }
  674. }
  675. rows = joined
  676. // Handle JOINs within this tref too
  677. if tref.Join != nil {
  678. rows, err = e.executeJoins(tref, rows)
  679. if err != nil {
  680. return nil, err
  681. }
  682. }
  683. }
  684. // Apply WHERE after all joins. It is intentionally deferred past the base
  685. // scan for JOIN queries because the WHERE may reference joined-table columns.
  686. if effectiveWhere != nil {
  687. var filtered []storage.Row
  688. for _, row := range rows {
  689. val, _ := e.evalExpr(effectiveWhere, row)
  690. if toBool(val) {
  691. filtered = append(filtered, row)
  692. }
  693. }
  694. rows = filtered
  695. }
  696. }
  697. // Handle implicit cross joins (comma-separated FROM tables)
  698. if isMultiTable {
  699. // Build the column-set for each table so we can push WHERE conditions down.
  700. type tableInfo struct {
  701. alias string
  702. name string
  703. colsSet map[string]bool // lower-case column names for this table
  704. }
  705. allTableInfos := make([]tableInfo, len(stmt.From))
  706. for i, tref := range stmt.From {
  707. alias := tref.Alias
  708. if alias == "" {
  709. alias = tref.Name
  710. }
  711. sch, _ := e.session.GetSchema(tref.Name)
  712. cols := map[string]bool{}
  713. if sch != nil {
  714. for _, c := range sch.Columns {
  715. cols[strings.ToLower(c.Name)] = true
  716. }
  717. }
  718. allTableInfos[i] = tableInfo{alias: alias, name: tref.Name, colsSet: cols}
  719. }
  720. // Split WHERE into AND-clauses and determine which tables each clause touches.
  721. var andClauses []parser.Expr
  722. if stmt.Where != nil {
  723. andClauses = splitANDClauses(stmt.Where)
  724. }
  725. // For each table, collect conditions that reference only its own columns.
  726. tableFilters := make([][]parser.Expr, len(stmt.From))
  727. var crossFilters []parser.Expr
  728. for _, clause := range andClauses {
  729. refs := collectColumnRefs(clause)
  730. ownerIdx := -1
  731. cross := false
  732. for _, ref := range refs {
  733. colLower := strings.ToLower(ref)
  734. found := -1
  735. for i, ti := range allTableInfos {
  736. if ti.colsSet[colLower] {
  737. if found == -1 {
  738. found = i
  739. } else if found != i {
  740. cross = true
  741. break
  742. }
  743. }
  744. }
  745. if cross {
  746. break
  747. }
  748. if found != -1 {
  749. if ownerIdx == -1 {
  750. ownerIdx = found
  751. } else if ownerIdx != found {
  752. cross = true
  753. break
  754. }
  755. }
  756. }
  757. if cross || ownerIdx == -1 {
  758. crossFilters = append(crossFilters, clause)
  759. } else {
  760. tableFilters[ownerIdx] = append(tableFilters[ownerIdx], clause)
  761. }
  762. }
  763. // Build cross-condition adjacency: for each cross filter, record which table indices it touches.
  764. type crossEdge struct{ a, b int }
  765. var crossEdges []crossEdge
  766. for _, clause := range crossFilters {
  767. refs := collectColumnRefs(clause)
  768. touched := map[int]bool{}
  769. for _, ref := range refs {
  770. cl := strings.ToLower(ref)
  771. for j, ti := range allTableInfos {
  772. if ti.colsSet[cl] {
  773. touched[j] = true
  774. }
  775. }
  776. }
  777. idxs := make([]int, 0, len(touched))
  778. for j := range touched {
  779. idxs = append(idxs, j)
  780. }
  781. if len(idxs) == 2 {
  782. crossEdges = append(crossEdges, crossEdge{idxs[0], idxs[1]})
  783. }
  784. }
  785. // Build alias-to-index map for applyWhenSeen.
  786. aliasToIdx := make(map[string]int, len(allTableInfos))
  787. for i, ti := range allTableInfos {
  788. aliasToIdx[strings.ToLower(ti.alias)] = i
  789. }
  790. // Helper: find cross-conditions applicable when seenSet is fully present.
  791. // A condition is applicable only when ALL tables it references are in seenSet.
  792. // For table-qualified refs (e.g. cor0.col2), we check the qualifying alias is seen.
  793. applyWhenSeen := func(seenSet map[int]bool, pending []parser.Expr) (applicable, still []parser.Expr) {
  794. for _, clause := range pending {
  795. tableRefs := collectTableColumnRefs(clause)
  796. ok := true
  797. for _, tr := range tableRefs {
  798. col := strings.ToLower(tr.col)
  799. tbl := strings.ToLower(tr.tbl)
  800. found := false
  801. if tbl != "" {
  802. // Explicit table qualifier — check that qualifying alias is seen.
  803. if idx, exists := aliasToIdx[tbl]; exists && seenSet[idx] {
  804. found = true
  805. }
  806. } else {
  807. // Unqualified — any seen table with this column satisfies it.
  808. for j, tti := range allTableInfos {
  809. if tti.colsSet[col] && seenSet[j] {
  810. found = true
  811. break
  812. }
  813. }
  814. }
  815. if !found {
  816. ok = false
  817. break
  818. }
  819. }
  820. if ok {
  821. applicable = append(applicable, clause)
  822. } else {
  823. still = append(still, clause)
  824. }
  825. }
  826. return
  827. }
  828. // Helper: inline cross-join two row-sets, applying a predicate.
  829. inlineJoin := func(left, right []storage.Row, pred parser.Expr) []storage.Row {
  830. out := make([]storage.Row, 0, len(left))
  831. for _, l := range left {
  832. for _, r := range right {
  833. m := make(storage.Row, len(l)+len(r))
  834. for k, v := range l {
  835. m[k] = v
  836. }
  837. for k, v := range r {
  838. m[k] = v
  839. }
  840. if pred != nil {
  841. val, _ := e.evalExpr(pred, m)
  842. if !toBool(val) {
  843. continue
  844. }
  845. }
  846. out = append(out, m)
  847. }
  848. }
  849. return out
  850. }
  851. // Pre-join connected components of "cross-only" tables (0 single-table filters,
  852. // connected via cross conditions to other cross-only tables).
  853. // This prevents n^k explosions when bare tables are joined last.
  854. crossOnlySet := map[int]bool{}
  855. for i := range stmt.From {
  856. if len(tableFilters[i]) > 0 {
  857. continue
  858. }
  859. for _, ce := range crossEdges {
  860. if ce.a == i || ce.b == i {
  861. crossOnlySet[i] = true
  862. break
  863. }
  864. }
  865. }
  866. // BFS: find connected components among cross-only tables.
  867. compOf := make([]int, len(stmt.From))
  868. for i := range compOf {
  869. compOf[i] = -1
  870. }
  871. nComps := 0
  872. for start := range stmt.From {
  873. if !crossOnlySet[start] || compOf[start] != -1 {
  874. continue
  875. }
  876. queue := []int{start}
  877. compOf[start] = nComps
  878. for len(queue) > 0 {
  879. cur := queue[0]
  880. queue = queue[1:]
  881. for _, ce := range crossEdges {
  882. var nb int = -1
  883. if ce.a == cur && crossOnlySet[ce.b] {
  884. nb = ce.b
  885. } else if ce.b == cur && crossOnlySet[ce.a] {
  886. nb = ce.a
  887. }
  888. if nb >= 0 && compOf[nb] == -1 {
  889. compOf[nb] = nComps
  890. queue = append(queue, nb)
  891. }
  892. }
  893. }
  894. nComps++
  895. }
  896. // Group cross-only tables by component.
  897. compTbls := make([][]int, nComps)
  898. for i, c := range compOf {
  899. if c >= 0 {
  900. compTbls[c] = append(compTbls[c], i)
  901. }
  902. }
  903. // Pre-join each component with ≥2 tables; collect results as virtual units.
  904. type virtualUnit struct {
  905. tableIdxs map[int]bool
  906. rows []storage.Row
  907. }
  908. var virtuals []virtualUnit
  909. preJoined := map[int]bool{} // original table indices consumed into virtuals
  910. remaining := make([]parser.Expr, len(crossFilters))
  911. copy(remaining, crossFilters)
  912. for _, comp := range compTbls {
  913. if len(comp) < 2 {
  914. continue
  915. }
  916. // Pick seed: table with most cross-edges within component.
  917. seed := comp[0]
  918. for _, idx := range comp[1:] {
  919. degIdx, degSeed := 0, 0
  920. for _, ce := range crossEdges {
  921. if ce.a == idx || ce.b == idx {
  922. degIdx++
  923. }
  924. if ce.a == seed || ce.b == seed {
  925. degSeed++
  926. }
  927. }
  928. if degIdx > degSeed {
  929. seed = idx
  930. }
  931. }
  932. // Load seed.
  933. seedRows, rerr := e.session.Select(stmt.From[seed].Name, nil)
  934. if rerr != nil {
  935. return nil, rerr
  936. }
  937. seedSchema, _ := e.session.GetSchema(stmt.From[seed].Name)
  938. for j := range seedRows {
  939. normalizeRowBySchema(seedRows[j], seedSchema)
  940. seedRows[j] = e.addTableAlias(seedRows[j], allTableInfos[seed].alias)
  941. }
  942. vSeen := map[int]bool{seed: true}
  943. // Greedy within-component join.
  944. compSet := map[int]bool{}
  945. for _, idx := range comp {
  946. compSet[idx] = true
  947. }
  948. for len(vSeen) < len(comp) {
  949. // Pick next table in component with cross-edge to vSeen.
  950. nextC := -1
  951. for _, idx := range comp {
  952. if vSeen[idx] {
  953. continue
  954. }
  955. for _, ce := range crossEdges {
  956. if (ce.a == idx && vSeen[ce.b]) || (ce.b == idx && vSeen[ce.a]) {
  957. nextC = idx
  958. break
  959. }
  960. }
  961. if nextC >= 0 {
  962. break
  963. }
  964. }
  965. if nextC < 0 {
  966. for _, idx := range comp {
  967. if !vSeen[idx] {
  968. nextC = idx
  969. break
  970. }
  971. }
  972. }
  973. nextRows, rerr := e.session.Select(stmt.From[nextC].Name, nil)
  974. if rerr != nil {
  975. return nil, rerr
  976. }
  977. nextSchema, _ := e.session.GetSchema(stmt.From[nextC].Name)
  978. for j := range nextRows {
  979. normalizeRowBySchema(nextRows[j], nextSchema)
  980. nextRows[j] = e.addTableAlias(nextRows[j], allTableInfos[nextC].alias)
  981. }
  982. vSeen[nextC] = true
  983. appl, still := applyWhenSeen(vSeen, remaining)
  984. remaining = still
  985. var pred parser.Expr
  986. if len(appl) > 0 {
  987. pred = combineAND(appl)
  988. }
  989. seedRows = inlineJoin(seedRows, nextRows, pred)
  990. }
  991. virtuals = append(virtuals, virtualUnit{tableIdxs: vSeen, rows: seedRows})
  992. for idx := range vSeen {
  993. preJoined[idx] = true
  994. }
  995. }
  996. // Build greedy order for non-pre-joined tables.
  997. // Score: single-table filter count + 1000 × cross-edges to already-joined.
  998. orderNonPJ := make([]int, 0, len(stmt.From)-len(preJoined))
  999. inOrderNPJ := make([]bool, len(stmt.From))
  1000. best := -1
  1001. for j := range stmt.From {
  1002. if preJoined[j] {
  1003. continue
  1004. }
  1005. if best < 0 || len(tableFilters[j]) > len(tableFilters[best]) {
  1006. best = j
  1007. }
  1008. }
  1009. if best >= 0 {
  1010. orderNonPJ = append(orderNonPJ, best)
  1011. inOrderNPJ[best] = true
  1012. }
  1013. for len(orderNonPJ)+len(preJoined) < len(stmt.From) {
  1014. joined := map[int]bool{}
  1015. for _, idx := range orderNonPJ {
  1016. joined[idx] = true
  1017. }
  1018. nextIdx := -1
  1019. nextScore := -1
  1020. for j := range stmt.From {
  1021. if inOrderNPJ[j] || preJoined[j] {
  1022. continue
  1023. }
  1024. score := len(tableFilters[j])
  1025. for _, ce := range crossEdges {
  1026. if (ce.a == j && joined[ce.b]) || (ce.b == j && joined[ce.a]) {
  1027. score += 1000
  1028. }
  1029. }
  1030. if score > nextScore {
  1031. nextScore = score
  1032. nextIdx = j
  1033. }
  1034. }
  1035. if nextIdx < 0 {
  1036. for j := range stmt.From {
  1037. if !inOrderNPJ[j] && !preJoined[j] {
  1038. nextIdx = j
  1039. break
  1040. }
  1041. }
  1042. }
  1043. if nextIdx >= 0 {
  1044. orderNonPJ = append(orderNonPJ, nextIdx)
  1045. inOrderNPJ[nextIdx] = true
  1046. }
  1047. }
  1048. // Load the initial rows for the first non-pre-joined table (or use the already-loaded rows).
  1049. seenTables := map[int]bool{}
  1050. if len(orderNonPJ) > 0 {
  1051. first := orderNonPJ[0]
  1052. if first != 0 {
  1053. rows, err = e.session.Select(stmt.From[first].Name, nil)
  1054. if err != nil {
  1055. return nil, err
  1056. }
  1057. firstSchema, _ := e.session.GetSchema(stmt.From[first].Name)
  1058. for i := range rows {
  1059. normalizeRowBySchema(rows[i], firstSchema)
  1060. rows[i] = e.addTableAlias(rows[i], allTableInfos[first].alias)
  1061. }
  1062. }
  1063. if len(tableFilters[first]) > 0 {
  1064. pred := combineAND(tableFilters[first])
  1065. var filtered []storage.Row
  1066. for _, row := range rows {
  1067. val, _ := e.evalExpr(pred, row)
  1068. if toBool(val) {
  1069. filtered = append(filtered, row)
  1070. }
  1071. }
  1072. rows = filtered
  1073. }
  1074. seenTables[first] = true
  1075. // Join remaining non-pre-joined tables.
  1076. for _, idx := range orderNonPJ[1:] {
  1077. ti := allTableInfos[idx]
  1078. rightRows, rerr := e.session.Select(stmt.From[idx].Name, nil)
  1079. if rerr != nil {
  1080. return nil, rerr
  1081. }
  1082. rightSchema, _ := e.session.GetSchema(stmt.From[idx].Name)
  1083. for j := range rightRows {
  1084. normalizeRowBySchema(rightRows[j], rightSchema)
  1085. rightRows[j] = e.addTableAlias(rightRows[j], ti.alias)
  1086. }
  1087. if len(tableFilters[idx]) > 0 {
  1088. pred := combineAND(tableFilters[idx])
  1089. var filtered []storage.Row
  1090. for _, row := range rightRows {
  1091. val, _ := e.evalExpr(pred, row)
  1092. if toBool(val) {
  1093. filtered = append(filtered, row)
  1094. }
  1095. }
  1096. rightRows = filtered
  1097. }
  1098. seenTables[idx] = true
  1099. appl, still := applyWhenSeen(seenTables, remaining)
  1100. remaining = still
  1101. var pred parser.Expr
  1102. if len(appl) > 0 {
  1103. pred = combineAND(appl)
  1104. }
  1105. rows = inlineJoin(rows, rightRows, pred)
  1106. }
  1107. } else {
  1108. // All tables were pre-joined; start with empty placeholder.
  1109. rows = []storage.Row{{}}
  1110. }
  1111. // Integrate virtual (pre-joined) units into the result.
  1112. for _, vu := range virtuals {
  1113. for idx := range vu.tableIdxs {
  1114. seenTables[idx] = true
  1115. }
  1116. appl, still := applyWhenSeen(seenTables, remaining)
  1117. remaining = still
  1118. var pred parser.Expr
  1119. if len(appl) > 0 {
  1120. pred = combineAND(appl)
  1121. }
  1122. rows = inlineJoin(rows, vu.rows, pred)
  1123. }
  1124. // Apply any remaining conditions (shouldn't normally happen).
  1125. if len(remaining) > 0 {
  1126. pred := combineAND(remaining)
  1127. var filtered []storage.Row
  1128. for _, row := range rows {
  1129. val, _ := e.evalExpr(pred, row)
  1130. if toBool(val) {
  1131. filtered = append(filtered, row)
  1132. }
  1133. }
  1134. rows = filtered
  1135. }
  1136. // Also cross-join with any JOIN chains within FROM entries (mixed comma+JOIN syntax).
  1137. // We cannot use executeJoins here because the left rows already have qualified keys
  1138. // from the isMultiTable cross-join; re-aliasing the left side would corrupt them.
  1139. for _, tref := range stmt.From {
  1140. join := tref.Join
  1141. for join != nil && join.Table != nil {
  1142. rightRef := join.Table
  1143. rightRows, rerr := e.session.Select(rightRef.Name, nil)
  1144. if rerr != nil {
  1145. return nil, rerr
  1146. }
  1147. rightAlias := rightRef.Alias
  1148. if rightAlias == "" {
  1149. rightAlias = rightRef.Name
  1150. }
  1151. rightSchema, _ := e.session.GetSchema(rightRef.Name)
  1152. for j := range rightRows {
  1153. normalizeRowBySchema(rightRows[j], rightSchema)
  1154. rightRows[j] = e.addTableAlias(rightRows[j], rightAlias)
  1155. }
  1156. var joined []storage.Row
  1157. for _, l := range rows {
  1158. for _, r := range rightRows {
  1159. m := make(storage.Row, len(l)+len(r))
  1160. for k, v := range l {
  1161. m[k] = v
  1162. }
  1163. for k, v := range r {
  1164. if _, exists := m[k]; !exists {
  1165. m[k] = v
  1166. } else if strings.Contains(k, ".") {
  1167. m[k] = v // qualified keys from right always win
  1168. }
  1169. }
  1170. matches, merr := e.joinMatches(l, r, m, join)
  1171. if merr != nil {
  1172. return nil, merr
  1173. }
  1174. if !matches {
  1175. continue
  1176. }
  1177. joined = append(joined, m)
  1178. }
  1179. }
  1180. rows = joined
  1181. join = rightRef.Join
  1182. }
  1183. }
  1184. }
  1185. // Handle GROUP BY
  1186. if len(stmt.GroupBy) > 0 {
  1187. return e.executeGroupBy(stmt, rows, schema)
  1188. }
  1189. // Check for aggregate functions without GROUP BY
  1190. hasAggregate := e.hasAggregates(stmt.Columns)
  1191. if hasAggregate {
  1192. return e.executeAggregateSelect(stmt, rows, schema)
  1193. }
  1194. // Apply ORDER BY, LIMIT, and OFFSET.
  1195. rows = e.orderAndLimitRows(rows, stmt.OrderBy, stmt.Limit, stmt.Offset, stmt.Columns)
  1196. // Build result
  1197. result := NewResult("SELECT")
  1198. // For multi-table or JOIN queries, collect all table refs for SELECT * expansion.
  1199. hasJoin := len(stmt.From) > 0 && stmt.From[0].Join != nil
  1200. allTableRefs := collectAllTableRefs(stmt.From)
  1201. // Resolve qualified wildcard (table.*) projections once, keyed by qualifier,
  1202. // so names, types, and row values expand exactly the same columns.
  1203. tableStars, err := e.resolveTableStars(stmt.From, stmt.Columns)
  1204. if err != nil {
  1205. return nil, err
  1206. }
  1207. // Determine columns
  1208. for _, name := range e.selectColumnNames(stmt, schema, allTableRefs, isMultiTable, tableStars) {
  1209. result.AddColumn(name)
  1210. }
  1211. // Populate column types from schema metadata so protocol consumers can
  1212. // decode typed values (e.g. timestamps) even when the result set is empty.
  1213. if isMultiTable || hasJoin {
  1214. result.ColumnTypes = e.joinedSelectColumnTypes(stmt, allTableRefs)
  1215. } else {
  1216. result.ColumnTypes = selectColumnTypes(stmt, schema)
  1217. }
  1218. // Window functions in the projection are evaluated over the scanned rows
  1219. // before their per-row values are read.
  1220. windowValues, werr := e.computeWindowValues(stmt, rows)
  1221. if werr != nil {
  1222. return nil, werr
  1223. }
  1224. // Add rows - evaluate each select expression
  1225. for rowIdx, row := range rows {
  1226. values := make([]interface{}, 0)
  1227. for _, col := range stmt.Columns {
  1228. if col.Star {
  1229. if isMultiTable || hasJoin {
  1230. // For multi-table SELECT *, extract columns using qualified names
  1231. for _, tref := range allTableRefs {
  1232. sch, _ := e.session.GetSchema(tref.Name)
  1233. if sch != nil {
  1234. for _, c := range sch.Columns {
  1235. qualKey := tref.Alias + "." + c.Name
  1236. val, ok := row[qualKey]
  1237. if !ok {
  1238. val = row[c.Name]
  1239. }
  1240. values = append(values, val)
  1241. }
  1242. }
  1243. }
  1244. } else {
  1245. // For SELECT *, add all columns in order. A real column named
  1246. // oid/rowid/_rowid_ is an ordinary column here, not the hidden
  1247. // rowid alias, so use its own value key.
  1248. for _, c := range schema.Columns {
  1249. values = append(values, row[c.Name])
  1250. }
  1251. }
  1252. } else if col.TableStar != "" {
  1253. // Qualified wildcard (table.*): emit only that table's columns,
  1254. // resolving values via the effective alias, falling back to the
  1255. // unqualified key for single-table queries without an alias.
  1256. proj := tableStars[strings.ToUpper(col.TableStar)]
  1257. for _, c := range proj.cols {
  1258. val, ok := row[proj.prefix+"."+c.Name]
  1259. if !ok {
  1260. val = row[c.Name]
  1261. }
  1262. values = append(values, val)
  1263. }
  1264. } else if we, ok := col.Expr.(*parser.WindowExpr); ok {
  1265. values = append(values, windowValues[we][rowIdx])
  1266. } else {
  1267. // Evaluate the expression
  1268. val, err := e.evalExpr(col.Expr, row)
  1269. if err != nil {
  1270. return nil, err
  1271. }
  1272. values = append(values, val)
  1273. }
  1274. }
  1275. result.AddRow(values...)
  1276. }
  1277. // Apply DISTINCT if specified
  1278. if stmt.Distinct {
  1279. result.Rows = e.applyDistinct(result.Rows)
  1280. result.RowCount = len(result.Rows)
  1281. }
  1282. return result, nil
  1283. }
  1284. // executeCompound executes a compound SELECT (UNION / UNION ALL / INTERSECT / EXCEPT).
  1285. func (e *Executor) executeCompound(c *parser.CompoundSelect) (*Result, error) {
  1286. left, err := e.executeSelect(c.Left)
  1287. if err != nil {
  1288. return nil, err
  1289. }
  1290. right, err := e.executeSelect(c.Right)
  1291. if err != nil {
  1292. return nil, err
  1293. }
  1294. rowKey := func(row []interface{}) string {
  1295. parts := make([]string, len(row))
  1296. for i, v := range row {
  1297. if v == nil {
  1298. parts[i] = "\x00NULL"
  1299. } else {
  1300. parts[i] = fmt.Sprintf("%v", v)
  1301. }
  1302. }
  1303. return strings.Join(parts, "\x01")
  1304. }
  1305. result := NewResult("SELECT")
  1306. for _, col := range left.Columns {
  1307. result.AddColumn(col)
  1308. }
  1309. // A compound SELECT reports the left branch's projection metadata, as
  1310. // PostgreSQL does: the set operation does not retype its columns.
  1311. result.ColumnTypes = append([]string(nil), left.ColumnTypes...)
  1312. switch c.Op {
  1313. case parser.SetOpUnion:
  1314. seen := map[string]bool{}
  1315. for _, row := range left.Rows {
  1316. k := rowKey(row)
  1317. if !seen[k] {
  1318. seen[k] = true
  1319. result.AddRow(row...)
  1320. }
  1321. }
  1322. for _, row := range right.Rows {
  1323. k := rowKey(row)
  1324. if !seen[k] {
  1325. seen[k] = true
  1326. result.AddRow(row...)
  1327. }
  1328. }
  1329. case parser.SetOpUnionAll:
  1330. for _, row := range left.Rows {
  1331. result.AddRow(row...)
  1332. }
  1333. for _, row := range right.Rows {
  1334. result.AddRow(row...)
  1335. }
  1336. case parser.SetOpIntersect:
  1337. rightSet := map[string]bool{}
  1338. for _, row := range right.Rows {
  1339. rightSet[rowKey(row)] = true
  1340. }
  1341. seen := map[string]bool{}
  1342. for _, row := range left.Rows {
  1343. k := rowKey(row)
  1344. if rightSet[k] && !seen[k] {
  1345. seen[k] = true
  1346. result.AddRow(row...)
  1347. }
  1348. }
  1349. case parser.SetOpExcept:
  1350. rightSet := map[string]bool{}
  1351. for _, row := range right.Rows {
  1352. rightSet[rowKey(row)] = true
  1353. }
  1354. seen := map[string]bool{}
  1355. for _, row := range left.Rows {
  1356. k := rowKey(row)
  1357. if !rightSet[k] && !seen[k] {
  1358. seen[k] = true
  1359. result.AddRow(row...)
  1360. }
  1361. }
  1362. }
  1363. // Apply compound-level ORDER BY / LIMIT / OFFSET if present.
  1364. if len(c.OrderBy) > 0 {
  1365. e.sortResultRows(result, c.OrderBy, nil, nil)
  1366. }
  1367. if c.Limit != nil {
  1368. limitVal, err := e.evalExpr(c.Limit, nil)
  1369. if err == nil {
  1370. limit := int(toFloat(limitVal))
  1371. if limit < len(result.Rows) {
  1372. result.Rows = result.Rows[:limit]
  1373. }
  1374. }
  1375. }
  1376. if c.Offset != nil {
  1377. offsetVal, err := e.evalExpr(c.Offset, nil)
  1378. if err == nil {
  1379. offset := int(toFloat(offsetVal))
  1380. if offset >= len(result.Rows) {
  1381. result.Rows = nil
  1382. } else if offset > 0 {
  1383. result.Rows = result.Rows[offset:]
  1384. }
  1385. }
  1386. }
  1387. return result, nil
  1388. }
  1389. // executeSelectExpr executes a SELECT without FROM.
  1390. func (e *Executor) executeSelectExpr(stmt *parser.SelectStmt) (*Result, error) {
  1391. // If any column contains an aggregate, treat as single-group aggregate over one implicit row.
  1392. if e.hasAggregates(stmt.Columns) {
  1393. return e.executeAggregateSelect(stmt, []storage.Row{{}}, nil)
  1394. }
  1395. result := NewResult("SELECT")
  1396. // Determine columns
  1397. for i, col := range stmt.Columns {
  1398. if col.Alias != "" {
  1399. result.AddColumn(col.Alias)
  1400. } else {
  1401. result.AddColumn(fmt.Sprintf("column%d", i+1))
  1402. }
  1403. // A SELECT without FROM has no schema, but literal and operator
  1404. // projections still have a known type.
  1405. result.ColumnTypes = append(result.ColumnTypes, inferExprType(col.Expr, nil))
  1406. }
  1407. // Evaluate expressions
  1408. values := make([]interface{}, len(stmt.Columns))
  1409. for i, col := range stmt.Columns {
  1410. val, err := e.evalExpr(col.Expr, nil)
  1411. if err != nil {
  1412. return nil, err
  1413. }
  1414. values[i] = val
  1415. }
  1416. result.AddRow(values...)
  1417. return result, nil
  1418. }
  1419. // executeSelectFromTableFunction materializes unnest(array) as a one-column
  1420. // relation and runs the rest of the SELECT over it. The parser restricts this
  1421. // form to a single FROM entry with no joins.
  1422. func (e *Executor) executeSelectFromTableFunction(stmt *parser.SelectStmt) (*Result, error) {
  1423. ref := stmt.From[0]
  1424. if !strings.EqualFold(ref.Function.Name, "unnest") {
  1425. return nil, pgerror.Unsupported("table function %s() is not supported", ref.Function.Name)
  1426. }
  1427. if len(ref.Function.Args) != 1 {
  1428. return nil, fmt.Errorf("unnest() requires exactly one array argument")
  1429. }
  1430. value, err := e.evalExpr(ref.Function.Args[0], nil)
  1431. if err != nil {
  1432. return nil, fmt.Errorf("unnest argument: %w", err)
  1433. }
  1434. elementType := "TEXT"
  1435. if typeName := inferExprType(ref.Function.Args[0], nil); typeName != "" {
  1436. if element, ok := arrayElementType(typeName); ok {
  1437. elementType = element
  1438. }
  1439. }
  1440. rows := make([][]interface{}, 0)
  1441. if value != nil {
  1442. elements, parseErr := parseArrayLiteral(toString(value))
  1443. if parseErr != nil {
  1444. return nil, fmt.Errorf("unnest requires an array value: %w", parseErr)
  1445. }
  1446. for _, element := range elements {
  1447. typed, valueErr := arrayElementValue(element, elementType)
  1448. if valueErr != nil {
  1449. return nil, fmt.Errorf("unnest element: %w", valueErr)
  1450. }
  1451. rows = append(rows, []interface{}{typed})
  1452. }
  1453. }
  1454. column := "unnest"
  1455. result, err := e.executeSelectOnMaterialized(stmt, []string{column}, rows)
  1456. if err != nil {
  1457. return nil, err
  1458. }
  1459. if len(result.Columns) == len(stmt.Columns) {
  1460. types := make([]string, 0, len(stmt.Columns))
  1461. for _, projection := range stmt.Columns {
  1462. if projection.Star {
  1463. types = append(types, elementType)
  1464. continue
  1465. }
  1466. types = append(types, inferExprType(projection.Expr, func(_, columnName string) (string, bool) {
  1467. if strings.EqualFold(columnName, column) {
  1468. return elementType, true
  1469. }
  1470. return "", false
  1471. }))
  1472. }
  1473. result.ColumnTypes = types
  1474. }
  1475. return result, nil
  1476. }
  1477. // executeSelectFromSubquery executes a SELECT with a subquery in FROM clause.
  1478. func (e *Executor) executeSelectFromSubquery(stmt *parser.SelectStmt) (*Result, error) {
  1479. // Execute the subquery to get the derived table
  1480. subqueryResult, err := e.executeSelect(stmt.From[0].Subquery)
  1481. if err != nil {
  1482. return nil, fmt.Errorf("subquery error: %w", err)
  1483. }
  1484. return e.executeSelectOnMaterialized(stmt, subqueryResult.Columns, subqueryResult.Rows)
  1485. }
  1486. func (e *Executor) executeSelectFromSubqueries(stmt *parser.SelectStmt) (*Result, error) {
  1487. rows := []storage.Row{{}}
  1488. var columns, starKeys []string
  1489. for _, ref := range stmt.From {
  1490. res, err := e.executeSelect(ref.Subquery)
  1491. if err != nil {
  1492. return nil, fmt.Errorf("subquery error: %w", err)
  1493. }
  1494. columns = append(columns, res.Columns...)
  1495. for _, column := range res.Columns {
  1496. starKeys = append(starKeys, ref.Alias+"."+column)
  1497. }
  1498. right := make([]storage.Row, 0, len(res.Rows))
  1499. for _, values := range res.Rows {
  1500. row := make(storage.Row, len(res.Columns))
  1501. for i, column := range res.Columns {
  1502. if i < len(values) {
  1503. row[column] = values[i]
  1504. }
  1505. }
  1506. right = append(right, e.addTableAlias(row, ref.Alias))
  1507. }
  1508. joined := make([]storage.Row, 0, len(rows)*len(right))
  1509. for _, leftRow := range rows {
  1510. for _, rightRow := range right {
  1511. row := make(storage.Row, len(leftRow)+len(rightRow))
  1512. for key, value := range leftRow {
  1513. row[key] = value
  1514. }
  1515. for key, value := range rightRow {
  1516. row[key] = value
  1517. }
  1518. joined = append(joined, row)
  1519. }
  1520. }
  1521. rows = joined
  1522. }
  1523. return e.executeSelectOnMaterializedRows(stmt, columns, starKeys, rows)
  1524. }
  1525. // executeSelectOnMaterialized runs a SELECT whose FROM[0] is already
  1526. // materialized as (columns, rowValues). It is shared by derived tables and
  1527. // materialized CTEs.
  1528. func (e *Executor) executeSelectOnMaterialized(stmt *parser.SelectStmt, columns []string, rowValues [][]interface{}) (*Result, error) {
  1529. derivedRows := make([]storage.Row, 0, len(rowValues))
  1530. for _, values := range rowValues {
  1531. row := make(storage.Row, len(columns))
  1532. for i, col := range columns {
  1533. if i < len(values) {
  1534. row[col] = values[i]
  1535. }
  1536. }
  1537. derivedRows = append(derivedRows, row)
  1538. }
  1539. return e.executeSelectOnMaterializedRows(stmt, columns, columns, derivedRows)
  1540. }
  1541. // executeSelectOnMaterializedCTEs cross-joins comma-separated CTEs while
  1542. // retaining qualified keys for expressions and a stable positional key for
  1543. // every SELECT * column, including duplicate column names.
  1544. func (e *Executor) executeSelectOnMaterializedCTEs(stmt *parser.SelectStmt) (*Result, error) {
  1545. rows := []storage.Row{{}}
  1546. var columns, starKeys []string
  1547. for _, ref := range stmt.From {
  1548. cte, _ := e.cteTableFor(ref.Name)
  1549. qualifier := ref.Alias
  1550. if qualifier == "" {
  1551. qualifier = ref.Name
  1552. }
  1553. columns = append(columns, cte.columns...)
  1554. for _, column := range cte.columns {
  1555. starKeys = append(starKeys, qualifier+"."+column)
  1556. }
  1557. right := cloneRows(cte.rows)
  1558. for i := range right {
  1559. right[i] = e.addTableAlias(right[i], qualifier)
  1560. }
  1561. joined := make([]storage.Row, 0, len(rows)*len(right))
  1562. for _, leftRow := range rows {
  1563. for _, rightRow := range right {
  1564. row := make(storage.Row, len(leftRow)+len(rightRow))
  1565. for key, value := range leftRow {
  1566. row[key] = value
  1567. }
  1568. for key, value := range rightRow {
  1569. row[key] = value
  1570. }
  1571. joined = append(joined, row)
  1572. }
  1573. }
  1574. rows = joined
  1575. }
  1576. return e.executeSelectOnMaterializedRows(stmt, columns, starKeys, rows)
  1577. }
  1578. func (e *Executor) executeSelectOnMaterializedRows(stmt *parser.SelectStmt, columns, starKeys []string, derivedRows []storage.Row) (*Result, error) {
  1579. // Handle JOINs if present
  1580. if stmt.From[0].Join != nil {
  1581. var err error
  1582. derivedRows, err = e.executeJoin(stmt.From[0], derivedRows)
  1583. if err != nil {
  1584. return nil, err
  1585. }
  1586. }
  1587. // Apply WHERE clause on derived table
  1588. if stmt.Where != nil {
  1589. filteredRows := make([]storage.Row, 0)
  1590. for _, row := range derivedRows {
  1591. val, err := e.evalExpr(stmt.Where, row)
  1592. if err != nil {
  1593. continue
  1594. }
  1595. if toBool(val) {
  1596. filteredRows = append(filteredRows, row)
  1597. }
  1598. }
  1599. derivedRows = filteredRows
  1600. }
  1601. // Handle GROUP BY
  1602. if len(stmt.GroupBy) > 0 {
  1603. return e.executeGroupBy(stmt, derivedRows, schemaFromColumns(columns))
  1604. }
  1605. // Check for aggregate functions without GROUP BY
  1606. if e.hasAggregates(stmt.Columns) {
  1607. return e.executeAggregateSelect(stmt, derivedRows, schemaFromColumns(columns))
  1608. }
  1609. // Apply ORDER BY, LIMIT, and OFFSET.
  1610. derivedRows = e.orderAndLimitRows(derivedRows, stmt.OrderBy, stmt.Limit, stmt.Offset, stmt.Columns)
  1611. // Build result. A projection may mix * and expressions, so each column is
  1612. // expanded independently.
  1613. result := NewResult("SELECT")
  1614. for _, col := range stmt.Columns {
  1615. switch {
  1616. case col.Star:
  1617. for _, c := range columns {
  1618. result.AddColumn(c)
  1619. }
  1620. case col.Alias != "":
  1621. result.AddColumn(col.Alias)
  1622. case col.Expr != nil:
  1623. if colRef, ok := col.Expr.(*parser.ColumnRef); ok {
  1624. result.AddColumn(colRef.Column)
  1625. } else {
  1626. result.AddColumn("column")
  1627. }
  1628. default:
  1629. result.AddColumn("column")
  1630. }
  1631. }
  1632. // Window functions in the projection are evaluated over the materialized
  1633. // rows before the values are read.
  1634. windowValues, err := e.computeWindowValues(stmt, derivedRows)
  1635. if err != nil {
  1636. return nil, err
  1637. }
  1638. for rowIdx, row := range derivedRows {
  1639. values := make([]interface{}, 0, len(stmt.Columns))
  1640. for _, col := range stmt.Columns {
  1641. switch {
  1642. case col.Star:
  1643. for _, key := range starKeys {
  1644. values = append(values, row[key])
  1645. }
  1646. case col.Expr != nil:
  1647. if we, ok := col.Expr.(*parser.WindowExpr); ok {
  1648. values = append(values, windowValues[we][rowIdx])
  1649. continue
  1650. }
  1651. val, err := e.evalExpr(col.Expr, row)
  1652. if err != nil {
  1653. return nil, err
  1654. }
  1655. values = append(values, val)
  1656. }
  1657. }
  1658. result.AddRow(values...)
  1659. }
  1660. return result, nil
  1661. }
  1662. // schemaFromColumns builds a schema with ANY-typed columns for materialized
  1663. // derived tables and CTEs.
  1664. func schemaFromColumns(columns []string) *storage.Schema {
  1665. schema := &storage.Schema{Name: "derived", Columns: make([]storage.Column, len(columns))}
  1666. for i, col := range columns {
  1667. schema.Columns[i] = storage.Column{Name: col, Type: "ANY"}
  1668. }
  1669. return schema
  1670. }
  1671. // executeAggregateSelect executes a SELECT with aggregate functions.
  1672. func (e *Executor) executeAggregateSelect(stmt *parser.SelectStmt, rows []storage.Row, schema *storage.Schema) (*Result, error) {
  1673. result := NewResult("SELECT")
  1674. resolve := schemaTypeResolver(schema)
  1675. // Determine columns and evaluate aggregates
  1676. for i, col := range stmt.Columns {
  1677. if col.Alias != "" {
  1678. result.AddColumn(col.Alias)
  1679. } else if col.Star {
  1680. result.AddColumn("*")
  1681. } else {
  1682. result.AddColumn(fmt.Sprintf("column%d", i+1))
  1683. }
  1684. if col.Star || col.TableStar != "" {
  1685. // The aggregate path emits one synthesized column per wildcard.
  1686. result.ColumnTypes = append(result.ColumnTypes, "TEXT")
  1687. continue
  1688. }
  1689. result.ColumnTypes = append(result.ColumnTypes, inferExprType(col.Expr, resolve))
  1690. }
  1691. // Calculate values
  1692. values := make([]interface{}, len(stmt.Columns))
  1693. for i, col := range stmt.Columns {
  1694. val, err := e.evalAggregateExpr(col.Expr, rows)
  1695. if err != nil {
  1696. return nil, err
  1697. }
  1698. values[i] = val
  1699. }
  1700. result.AddRow(values...)
  1701. return result, nil
  1702. }
  1703. // executeGroupBy executes a GROUP BY query.
  1704. func (e *Executor) executeGroupBy(stmt *parser.SelectStmt, rows []storage.Row, schema *storage.Schema) (*Result, error) {
  1705. result := NewResult("SELECT")
  1706. // Expand SELECT * if present
  1707. expandedColumns := make([]parser.SelectColumn, 0, len(stmt.Columns))
  1708. for _, col := range stmt.Columns {
  1709. if col.Star {
  1710. for _, c := range schema.Columns {
  1711. expandedColumns = append(expandedColumns, parser.SelectColumn{
  1712. Expr: &parser.ColumnRef{Column: c.Name},
  1713. })
  1714. }
  1715. } else if col.TableStar != "" {
  1716. // Qualified wildcard: expand only the named table's columns.
  1717. cols, prefix, err := e.resolveTableStar(stmt.From, col.TableStar)
  1718. if err != nil {
  1719. return nil, err
  1720. }
  1721. for _, c := range cols {
  1722. expandedColumns = append(expandedColumns, parser.SelectColumn{
  1723. Expr: &parser.ColumnRef{Table: prefix, Column: c.Name},
  1724. })
  1725. }
  1726. } else {
  1727. expandedColumns = append(expandedColumns, col)
  1728. }
  1729. }
  1730. // Determine column names
  1731. columnNames := make([]string, len(expandedColumns))
  1732. for i, col := range expandedColumns {
  1733. if col.Alias != "" {
  1734. columnNames[i] = col.Alias
  1735. result.AddColumn(col.Alias)
  1736. } else if ref, ok := col.Expr.(*parser.ColumnRef); ok {
  1737. columnNames[i] = ref.Column
  1738. result.AddColumn(ref.Column)
  1739. } else {
  1740. columnNames[i] = fmt.Sprintf("column%d", i+1)
  1741. result.AddColumn(columnNames[i])
  1742. }
  1743. }
  1744. // Populate column types from schema metadata, as the plain SELECT path
  1745. // does, so protocol clients can decode grouped timestamp/date columns.
  1746. result.ColumnTypes = make([]string, len(expandedColumns))
  1747. for i, col := range expandedColumns {
  1748. result.ColumnTypes[i] = projectionColumnType(col, schema)
  1749. }
  1750. // Resolve GROUP BY references that name a SELECT alias to the aliased
  1751. // expression, matching SQLite.
  1752. groupByExprs := e.resolveGroupByAliases(stmt.GroupBy, expandedColumns)
  1753. // Fast path: use running accumulators instead of collecting rows per group.
  1754. // Applicable when there is no HAVING clause and all aggregate SELECT columns
  1755. // are direct FunctionCalls (COUNT/SUM/AVG/MIN/MAX).
  1756. if e.canUseGroupAccum(stmt, expandedColumns) {
  1757. return e.executeGroupByAccum(stmt, rows, result, expandedColumns, columnNames, groupByExprs)
  1758. }
  1759. // Slow path: collect full rows per group then evaluate aggregates over them.
  1760. groups := make(map[string][]storage.Row)
  1761. for _, row := range rows {
  1762. key := e.buildGroupKey(groupByExprs, row)
  1763. groups[key] = append(groups[key], row)
  1764. }
  1765. for _, groupRows := range groups {
  1766. if stmt.Having != nil {
  1767. val, err := e.evalAggregateExpr(stmt.Having, groupRows)
  1768. if err != nil || val == nil || !toBool(val) {
  1769. continue
  1770. }
  1771. }
  1772. values := make([]interface{}, len(expandedColumns))
  1773. for i, col := range expandedColumns {
  1774. if e.isAggregate(col.Expr) {
  1775. val, err := e.evalAggregateExpr(col.Expr, groupRows)
  1776. if err != nil {
  1777. return nil, err
  1778. }
  1779. values[i] = val
  1780. } else {
  1781. val, err := e.evalExpr(col.Expr, groupRows[0])
  1782. if err != nil {
  1783. return nil, err
  1784. }
  1785. values[i] = val
  1786. }
  1787. }
  1788. result.AddRow(values...)
  1789. }
  1790. return e.finalizeGroupResult(stmt, result, expandedColumns, columnNames)
  1791. }
  1792. // canUseGroupAccum returns true when the fast accumulator path can handle the query.
  1793. func (e *Executor) canUseGroupAccum(stmt *parser.SelectStmt, expandedColumns []parser.SelectColumn) bool {
  1794. if stmt.Having != nil {
  1795. return false
  1796. }
  1797. for _, col := range expandedColumns {
  1798. if !e.isAggregate(col.Expr) {
  1799. continue
  1800. }
  1801. fn, ok := col.Expr.(*parser.FunctionCall)
  1802. if !ok {
  1803. return false
  1804. }
  1805. switch strings.ToUpper(fn.Name) {
  1806. case "COUNT", "SUM", "AVG", "MIN", "MAX":
  1807. default:
  1808. return false
  1809. }
  1810. }
  1811. return true
  1812. }
  1813. // aggColInfo pairs a SELECT column index with its aggregate FunctionCall.
  1814. type aggColInfo struct {
  1815. colIdx int
  1816. fn *parser.FunctionCall
  1817. }
  1818. // aggAccum holds running state for a single aggregate function.
  1819. type aggAccum struct {
  1820. count int64
  1821. sumI int64
  1822. sumF float64
  1823. allInt bool
  1824. hasVal bool
  1825. extreme interface{}
  1826. seen map[interface{}]struct{} // for DISTINCT
  1827. }
  1828. // groupAccumState holds per-group state for the fast accumulator path.
  1829. type groupAccumState struct {
  1830. firstRow storage.Row
  1831. accums []*aggAccum
  1832. }
  1833. // executeGroupByAccum is the fast GROUP BY path: increments per-group counters as rows
  1834. // arrive rather than materialising row slices, keeping O(1) state per group.
  1835. func (e *Executor) executeGroupByAccum(stmt *parser.SelectStmt, rows []storage.Row, result *Result, expandedColumns []parser.SelectColumn, columnNames []string, groupBy []parser.Expr) (*Result, error) {
  1836. var aggCols []aggColInfo
  1837. for i, col := range expandedColumns {
  1838. if e.isAggregate(col.Expr) {
  1839. aggCols = append(aggCols, aggColInfo{i, col.Expr.(*parser.FunctionCall)})
  1840. }
  1841. }
  1842. states := make(map[string]*groupAccumState, 64)
  1843. var keyOrder []string
  1844. for _, row := range rows {
  1845. key := e.buildGroupKey(groupBy, row)
  1846. state, exists := states[key]
  1847. if !exists {
  1848. accums := make([]*aggAccum, len(aggCols))
  1849. for j, ac := range aggCols {
  1850. a := &aggAccum{allInt: true}
  1851. if ac.fn.Distinct {
  1852. a.seen = make(map[interface{}]struct{})
  1853. }
  1854. accums[j] = a
  1855. }
  1856. state = &groupAccumState{firstRow: row, accums: accums}
  1857. states[key] = state
  1858. keyOrder = append(keyOrder, key)
  1859. }
  1860. for j, ac := range aggCols {
  1861. e.feedAggAccum(state.accums[j], ac.fn, row)
  1862. }
  1863. }
  1864. for _, key := range keyOrder {
  1865. state := states[key]
  1866. values := make([]interface{}, len(expandedColumns))
  1867. for i, col := range expandedColumns {
  1868. if e.isAggregate(col.Expr) {
  1869. for j, ac := range aggCols {
  1870. if ac.colIdx == i {
  1871. values[i] = finalizeAggAccum(state.accums[j], ac.fn)
  1872. break
  1873. }
  1874. }
  1875. } else {
  1876. val, _ := e.evalExpr(col.Expr, state.firstRow)
  1877. values[i] = val
  1878. }
  1879. }
  1880. result.AddRow(values...)
  1881. }
  1882. return e.finalizeGroupResult(stmt, result, expandedColumns, columnNames)
  1883. }
  1884. // feedAggAccum updates a running accumulator with one row.
  1885. func (e *Executor) feedAggAccum(a *aggAccum, fn *parser.FunctionCall, row storage.Row) {
  1886. switch strings.ToUpper(fn.Name) {
  1887. case "COUNT":
  1888. if fn.Star {
  1889. a.count++
  1890. return
  1891. }
  1892. if len(fn.Args) == 0 {
  1893. return
  1894. }
  1895. val, _ := e.evalExpr(fn.Args[0], row)
  1896. if val == nil {
  1897. return
  1898. }
  1899. if fn.Distinct {
  1900. k := fmt.Sprintf("%v", val)
  1901. if _, exists := a.seen[k]; exists {
  1902. return
  1903. }
  1904. a.seen[k] = struct{}{}
  1905. }
  1906. a.count++
  1907. case "SUM":
  1908. if len(fn.Args) == 0 {
  1909. return
  1910. }
  1911. val, _ := e.evalExpr(fn.Args[0], row)
  1912. if val == nil {
  1913. return
  1914. }
  1915. if fn.Distinct {
  1916. k := fmt.Sprintf("%v", val)
  1917. if _, exists := a.seen[k]; exists {
  1918. return
  1919. }
  1920. a.seen[k] = struct{}{}
  1921. }
  1922. if isIntVal(val) {
  1923. a.sumI += toInt64(val)
  1924. } else {
  1925. a.allInt = false
  1926. a.sumF += toFloat(val)
  1927. }
  1928. a.hasVal = true
  1929. case "AVG":
  1930. if len(fn.Args) == 0 {
  1931. return
  1932. }
  1933. val, _ := e.evalExpr(fn.Args[0], row)
  1934. if val == nil {
  1935. return
  1936. }
  1937. a.sumF += toFloat(val)
  1938. a.count++
  1939. a.hasVal = true
  1940. case "MIN":
  1941. if len(fn.Args) == 0 {
  1942. return
  1943. }
  1944. val, _ := e.evalExpr(fn.Args[0], row)
  1945. if val != nil && (a.extreme == nil || compare(val, a.extreme) < 0) {
  1946. a.extreme = val
  1947. }
  1948. case "MAX":
  1949. if len(fn.Args) == 0 {
  1950. return
  1951. }
  1952. val, _ := e.evalExpr(fn.Args[0], row)
  1953. if val != nil && (a.extreme == nil || compare(val, a.extreme) > 0) {
  1954. a.extreme = val
  1955. }
  1956. }
  1957. }
  1958. // finalizeAggAccum computes the final aggregate value from a running accumulator.
  1959. func finalizeAggAccum(a *aggAccum, fn *parser.FunctionCall) interface{} {
  1960. switch strings.ToUpper(fn.Name) {
  1961. case "COUNT":
  1962. return a.count
  1963. case "SUM":
  1964. if !a.hasVal {
  1965. return nil
  1966. }
  1967. if a.allInt {
  1968. return a.sumI
  1969. }
  1970. return a.sumF + float64(a.sumI)
  1971. case "AVG":
  1972. if !a.hasVal || a.count == 0 {
  1973. return nil
  1974. }
  1975. return a.sumF / float64(a.count)
  1976. case "MIN", "MAX":
  1977. return a.extreme
  1978. }
  1979. return nil
  1980. }
  1981. // finalizeGroupResult applies DISTINCT, ORDER BY, and LIMIT/OFFSET to a GROUP BY result.
  1982. func (e *Executor) finalizeGroupResult(stmt *parser.SelectStmt, result *Result, expandedColumns []parser.SelectColumn, columnNames []string) (*Result, error) {
  1983. if stmt.Distinct {
  1984. result.Rows = e.applyDistinct(result.Rows)
  1985. }
  1986. e.orderAndLimitResultRows(result, stmt.OrderBy, stmt.Limit, stmt.Offset, expandedColumns, columnNames)
  1987. return result, nil
  1988. }
  1989. // executeJoins recursively processes all JOIN clauses in a table reference.
  1990. func (e *Executor) executeJoins(tableRef parser.TableRef, leftRows []storage.Row) ([]storage.Row, error) {
  1991. return e.executeJoinsWithMode(tableRef, leftRows, true)
  1992. }
  1993. func (e *Executor) executeJoinsWithMode(tableRef parser.TableRef, leftRows []storage.Row, qualifyLeft bool) ([]storage.Row, error) {
  1994. if tableRef.Join == nil || tableRef.Join.Table == nil {
  1995. return leftRows, nil
  1996. }
  1997. // Get the right table name. Equality joins against its primary key can probe
  1998. // only the referenced rows instead of scanning the whole table.
  1999. rightTableRef := tableRef.Join.Table
  2000. rightTable := rightTableRef.Name
  2001. // Perform the join between left and right
  2002. var result []storage.Row
  2003. leftTableName := tableRef.Name
  2004. leftAlias := tableRef.Alias
  2005. rightAlias := rightTableRef.Alias
  2006. // If leftAlias is empty, use the table name
  2007. if leftAlias == "" {
  2008. leftAlias = leftTableName
  2009. }
  2010. if rightAlias == "" {
  2011. rightAlias = rightTable
  2012. }
  2013. leftAliasForMerge := leftAlias
  2014. if !qualifyLeft {
  2015. leftAliasForMerge = ""
  2016. }
  2017. // Build a synthetic TableRef so we can reuse extractEqualityJoinKeys.
  2018. syntheticLeft := parser.TableRef{Name: leftTableName, Alias: leftAlias}
  2019. syntheticJoin := &parser.JoinClause{
  2020. Type: tableRef.Join.Type,
  2021. Table: &parser.TableRef{Name: rightTable, Alias: rightAlias},
  2022. Condition: tableRef.Join.Condition,
  2023. }
  2024. leftKey, rightKey, canHash := extractEqualityJoinKeys(tableRef.Join.Condition, syntheticLeft, syntheticJoin)
  2025. if len(tableRef.Join.Using) > 0 {
  2026. canHash = false
  2027. }
  2028. var rightRows []storage.Row
  2029. var rightSchema *storage.Schema
  2030. var err error
  2031. switch {
  2032. case rightTableRef.Subquery != nil:
  2033. rightRows, rightSchema, err = e.materializeJoinSubquery(rightTableRef)
  2034. if err != nil {
  2035. return nil, err
  2036. }
  2037. case e.cteTableExists(rightTable):
  2038. cte, _ := e.cteTableFor(rightTable)
  2039. rightRows = cloneRows(cte.rows)
  2040. rightSchema = schemaFromColumns(cte.columns)
  2041. default:
  2042. rightSchema, err = e.session.GetSchema(rightTable)
  2043. if err != nil {
  2044. return nil, err
  2045. }
  2046. if canHash && rightSchema.IsSingleColumnPrimaryKey() && strings.EqualFold(rightSchema.PrimaryKey, rightKey) && len(leftRows) <= 256 {
  2047. seen := make(map[string]bool, len(leftRows))
  2048. for _, left := range leftRows {
  2049. key := joinKeyString(left, leftKey)
  2050. if key == "\x00" || seen[key] {
  2051. continue
  2052. }
  2053. seen[key] = true
  2054. row, getErr := e.session.GetByPK(rightTable, key)
  2055. if getErr == storage.ErrKeyNotFound {
  2056. continue
  2057. }
  2058. if getErr != nil {
  2059. return nil, getErr
  2060. }
  2061. normalizeRowBySchema(row, rightSchema)
  2062. rightRows = append(rightRows, row)
  2063. }
  2064. } else {
  2065. rightRows, err = e.session.Select(rightTable, nil)
  2066. if err != nil {
  2067. return nil, err
  2068. }
  2069. for _, row := range rightRows {
  2070. normalizeRowBySchema(row, rightSchema)
  2071. }
  2072. }
  2073. }
  2074. switch tableRef.Join.Type {
  2075. case parser.JoinInner:
  2076. if canHash {
  2077. hashTable := make(map[string][]storage.Row, len(rightRows))
  2078. for _, right := range rightRows {
  2079. k := joinKeyString(right, rightKey)
  2080. hashTable[k] = append(hashTable[k], right)
  2081. }
  2082. for _, left := range leftRows {
  2083. k := joinKeyString(left, leftKey)
  2084. for _, right := range hashTable[k] {
  2085. result = append(result, e.mergeRows(left, right, leftAliasForMerge, rightAlias))
  2086. }
  2087. }
  2088. } else {
  2089. for _, left := range leftRows {
  2090. for _, right := range rightRows {
  2091. merged := e.mergeRows(left, right, leftAliasForMerge, rightAlias)
  2092. match, err := e.joinMatches(left, right, merged, tableRef.Join)
  2093. if err != nil {
  2094. return nil, err
  2095. }
  2096. if match {
  2097. result = append(result, merged)
  2098. }
  2099. }
  2100. }
  2101. }
  2102. case parser.JoinLeft:
  2103. if canHash {
  2104. hashTable := make(map[string][]storage.Row, len(rightRows))
  2105. for _, right := range rightRows {
  2106. k := joinKeyString(right, rightKey)
  2107. hashTable[k] = append(hashTable[k], right)
  2108. }
  2109. nullRight := makeNullRow(rightRows, rightTable, e)
  2110. for _, left := range leftRows {
  2111. k := joinKeyString(left, leftKey)
  2112. matches := hashTable[k]
  2113. if len(matches) == 0 {
  2114. result = append(result, e.mergeRows(left, nullRight, leftAliasForMerge, rightAlias))
  2115. } else {
  2116. for _, right := range matches {
  2117. result = append(result, e.mergeRows(left, right, leftAliasForMerge, rightAlias))
  2118. }
  2119. }
  2120. }
  2121. } else {
  2122. for _, left := range leftRows {
  2123. matched := false
  2124. for _, right := range rightRows {
  2125. merged := e.mergeRows(left, right, leftAliasForMerge, rightAlias)
  2126. match, err := e.joinMatches(left, right, merged, tableRef.Join)
  2127. if err != nil {
  2128. return nil, err
  2129. }
  2130. if match {
  2131. result = append(result, merged)
  2132. matched = true
  2133. }
  2134. }
  2135. if !matched {
  2136. nullRight := makeNullRow(rightRows, rightTable, e)
  2137. result = append(result, e.mergeRows(left, nullRight, leftAliasForMerge, rightAlias))
  2138. }
  2139. }
  2140. }
  2141. case parser.JoinCross:
  2142. for _, left := range leftRows {
  2143. for _, right := range rightRows {
  2144. result = append(result, e.mergeRows(left, right, leftAliasForMerge, rightAlias))
  2145. }
  2146. }
  2147. }
  2148. // Recursively process any additional joins
  2149. if rightTableRef.Join != nil {
  2150. return e.executeJoinsWithMode(*rightTableRef, result, false)
  2151. }
  2152. return result, nil
  2153. }
  2154. // executeJoin executes a JOIN operation.
  2155. func (e *Executor) executeJoin(tableRef parser.TableRef, leftRows []storage.Row) ([]storage.Row, error) {
  2156. join := tableRef.Join
  2157. if join == nil || join.Table == nil {
  2158. return leftRows, nil
  2159. }
  2160. rightTable := join.Table.Name
  2161. var rightRows []storage.Row
  2162. var err error
  2163. switch {
  2164. case join.Table.Subquery != nil:
  2165. rightRows, _, err = e.materializeJoinSubquery(join.Table)
  2166. case e.cteTableExists(rightTable):
  2167. cte, _ := e.cteTableFor(rightTable)
  2168. rightRows = cloneRows(cte.rows)
  2169. default:
  2170. rightRows, err = e.session.Select(rightTable, nil)
  2171. }
  2172. if err != nil {
  2173. return nil, err
  2174. }
  2175. var result []storage.Row
  2176. switch join.Type {
  2177. case parser.JoinInner:
  2178. leftKey, rightKey, canHash := extractEqualityJoinKeys(join.Condition, tableRef, join)
  2179. if len(join.Using) > 0 {
  2180. canHash = false
  2181. }
  2182. if canHash {
  2183. // Hash join: build phase on right, probe phase on left — O(N+M) vs O(N*M)
  2184. hashTable := make(map[string][]storage.Row, len(rightRows))
  2185. for _, right := range rightRows {
  2186. k := joinKeyString(right, rightKey)
  2187. hashTable[k] = append(hashTable[k], right)
  2188. }
  2189. for _, left := range leftRows {
  2190. k := joinKeyString(left, leftKey)
  2191. for _, right := range hashTable[k] {
  2192. result = append(result, e.mergeRows(left, right, tableRef.Alias, join.Table.Alias))
  2193. }
  2194. }
  2195. } else {
  2196. for _, left := range leftRows {
  2197. for _, right := range rightRows {
  2198. merged := e.mergeRows(left, right, tableRef.Alias, join.Table.Alias)
  2199. match, err := e.joinMatches(left, right, merged, join)
  2200. if err != nil {
  2201. return nil, err
  2202. }
  2203. if match {
  2204. result = append(result, merged)
  2205. }
  2206. }
  2207. }
  2208. }
  2209. case parser.JoinLeft:
  2210. leftKey, rightKey, canHash := extractEqualityJoinKeys(join.Condition, tableRef, join)
  2211. if len(join.Using) > 0 {
  2212. canHash = false
  2213. }
  2214. if canHash {
  2215. hashTable := make(map[string][]storage.Row, len(rightRows))
  2216. for _, right := range rightRows {
  2217. k := joinKeyString(right, rightKey)
  2218. hashTable[k] = append(hashTable[k], right)
  2219. }
  2220. nullRight := makeNullRow(rightRows, rightTable, e)
  2221. for _, left := range leftRows {
  2222. k := joinKeyString(left, leftKey)
  2223. matches := hashTable[k]
  2224. if len(matches) == 0 {
  2225. result = append(result, e.mergeRows(left, nullRight, tableRef.Alias, join.Table.Alias))
  2226. } else {
  2227. for _, right := range matches {
  2228. result = append(result, e.mergeRows(left, right, tableRef.Alias, join.Table.Alias))
  2229. }
  2230. }
  2231. }
  2232. } else {
  2233. for _, left := range leftRows {
  2234. matched := false
  2235. for _, right := range rightRows {
  2236. merged := e.mergeRows(left, right, tableRef.Alias, join.Table.Alias)
  2237. match, err := e.joinMatches(left, right, merged, join)
  2238. if err != nil {
  2239. return nil, err
  2240. }
  2241. if match {
  2242. result = append(result, merged)
  2243. matched = true
  2244. }
  2245. }
  2246. if !matched {
  2247. nullRight := makeNullRow(rightRows, rightTable, e)
  2248. result = append(result, e.mergeRows(left, nullRight, tableRef.Alias, join.Table.Alias))
  2249. }
  2250. }
  2251. }
  2252. case parser.JoinCross:
  2253. for _, left := range leftRows {
  2254. for _, right := range rightRows {
  2255. result = append(result, e.mergeRows(left, right, tableRef.Alias, join.Table.Alias))
  2256. }
  2257. }
  2258. }
  2259. return result, nil
  2260. }
  2261. func (e *Executor) joinMatches(left, right, merged storage.Row, join *parser.JoinClause) (bool, error) {
  2262. if join.Condition != nil {
  2263. match, err := e.evalExpr(join.Condition, merged)
  2264. return toBool(match), err
  2265. }
  2266. for _, column := range join.Using {
  2267. leftValue, leftOK := lookupRowValue(left, column)
  2268. rightValue, rightOK := lookupRowValue(right, column)
  2269. if !leftOK || !rightOK || leftValue == nil || rightValue == nil || compare(leftValue, rightValue) != 0 {
  2270. return false, nil
  2271. }
  2272. }
  2273. return true, nil
  2274. }
  2275. // extractEqualityJoinKeys checks if a JOIN condition is a simple col = col equality
  2276. // and returns the key names to probe in left rows and build from right rows.
  2277. func extractEqualityJoinKeys(condition parser.Expr, leftRef parser.TableRef, join *parser.JoinClause) (leftKey, rightKey string, ok bool) {
  2278. if condition == nil {
  2279. return "", "", false
  2280. }
  2281. bin, isBin := condition.(*parser.BinaryExpr)
  2282. if !isBin || bin.Op != lexer.TokenEq {
  2283. return "", "", false
  2284. }
  2285. lRef, leftIsCol := bin.Left.(*parser.ColumnRef)
  2286. rRef, rightIsCol := bin.Right.(*parser.ColumnRef)
  2287. if !leftIsCol || !rightIsCol {
  2288. return "", "", false
  2289. }
  2290. leftAlias := leftRef.Alias
  2291. leftName := leftRef.Name
  2292. rightAlias := join.Table.Alias
  2293. rightName := join.Table.Name
  2294. leftJoinKey := func(r *parser.ColumnRef) (string, bool) {
  2295. if r.Table == "" || r.Table == leftAlias || r.Table == leftName {
  2296. return r.Column, true
  2297. }
  2298. // In a chained explicit JOIN, the left row already contains every table
  2299. // joined so far. Preserve qualified references such as "o.id" so joins
  2300. // against earlier tables can still use the hash path.
  2301. if r.Table != rightAlias && r.Table != rightName {
  2302. return r.Table + "." + r.Column, true
  2303. }
  2304. return "", false
  2305. }
  2306. rightJoinKey := func(r *parser.ColumnRef) (string, bool) {
  2307. if r.Table == "" || r.Table == rightAlias || r.Table == rightName {
  2308. return r.Column, true
  2309. }
  2310. return "", false
  2311. }
  2312. if lk, leftOK := leftJoinKey(lRef); leftOK {
  2313. if rk, rightOK := rightJoinKey(rRef); rightOK {
  2314. return lk, rk, true
  2315. }
  2316. }
  2317. if lk, leftOK := leftJoinKey(rRef); leftOK {
  2318. if rk, rightOK := rightJoinKey(lRef); rightOK {
  2319. return lk, rk, true
  2320. }
  2321. }
  2322. return "", "", false
  2323. }
  2324. // joinKeyString returns a string representation of a row's join key for hashing.
  2325. func joinKeyString(row storage.Row, col string) string {
  2326. if v, ok := row[col]; ok {
  2327. return fmt.Sprintf("%v", v)
  2328. }
  2329. return "\x00"
  2330. }
  2331. // makeNullRow builds a null-valued row based on the right table's rows or schema.
  2332. func makeNullRow(rightRows []storage.Row, rightTable string, e *Executor) storage.Row {
  2333. nullRight := make(storage.Row)
  2334. if len(rightRows) > 0 {
  2335. for k := range rightRows[0] {
  2336. nullRight[k] = nil
  2337. }
  2338. } else {
  2339. rightSchema, err := e.session.GetSchema(rightTable)
  2340. if err == nil {
  2341. for _, col := range rightSchema.Columns {
  2342. nullRight[col.Name] = nil
  2343. }
  2344. }
  2345. }
  2346. return nullRight
  2347. }
  2348. // mergeRows merges two rows with optional table aliases.
  2349. func (e *Executor) mergeRows(left, right storage.Row, leftAlias, rightAlias string) storage.Row {
  2350. result := make(storage.Row)
  2351. for k, v := range left {
  2352. // Copy the key as-is (it might already be qualified)
  2353. result[k] = v
  2354. // Only add qualified name if the key is NOT already qualified and we have an alias
  2355. if leftAlias != "" && !strings.Contains(k, ".") {
  2356. result[leftAlias+"."+k] = v
  2357. }
  2358. }
  2359. for k, v := range right {
  2360. // For unqualified names, only add if they don't already exist
  2361. // This prevents right table columns from overwriting left table columns
  2362. if !strings.Contains(k, ".") {
  2363. if _, exists := result[k]; !exists {
  2364. result[k] = v
  2365. }
  2366. // Add qualified name for right table
  2367. if rightAlias != "" {
  2368. result[rightAlias+"."+k] = v
  2369. }
  2370. } else {
  2371. // Already qualified, just copy it
  2372. result[k] = v
  2373. }
  2374. }
  2375. return result
  2376. }
  2377. // collectAllTableRefs returns a flat list of (alias, tableName) pairs for all tables
  2378. // referenced in a FROM clause, following both implicit (comma) and explicit JOIN chains.
  2379. func collectAllTableRefs(from []parser.TableRef) []parser.TableRef {
  2380. var refs []parser.TableRef
  2381. for _, tref := range from {
  2382. cur := tref
  2383. for {
  2384. // Shallow copy to hold only this table (no join chain)
  2385. flat := parser.TableRef{Name: cur.Name, Alias: cur.Alias}
  2386. if flat.Alias == "" {
  2387. flat.Alias = flat.Name
  2388. }
  2389. refs = append(refs, flat)
  2390. if cur.Join == nil || cur.Join.Table == nil {
  2391. break
  2392. }
  2393. cur = *cur.Join.Table
  2394. }
  2395. }
  2396. return refs
  2397. }
  2398. // starProjection is a resolved qualified wildcard: the table's columns and the
  2399. // row-key prefix used to read their values.
  2400. type starProjection struct {
  2401. cols []storage.Column
  2402. prefix string
  2403. }
  2404. // resolveTableStars resolves every qualified wildcard in a projection.
  2405. func (e *Executor) resolveTableStars(from []parser.TableRef, columns []parser.SelectColumn) (map[string]starProjection, error) {
  2406. stars := make(map[string]starProjection)
  2407. for _, col := range columns {
  2408. if col.TableStar == "" {
  2409. continue
  2410. }
  2411. key := strings.ToUpper(col.TableStar)
  2412. if _, ok := stars[key]; ok {
  2413. continue
  2414. }
  2415. cols, prefix, err := e.resolveTableStar(from, col.TableStar)
  2416. if err != nil {
  2417. return nil, err
  2418. }
  2419. stars[key] = starProjection{cols: cols, prefix: prefix}
  2420. }
  2421. return stars, nil
  2422. }
  2423. // selectColumnNames expands a projection into result column names using the
  2424. // same wildcard expansion as the row values: every joined table for an
  2425. // unqualified *, the resolved table for table.*, and the schema for a
  2426. // single-table *.
  2427. func (e *Executor) selectColumnNames(stmt *parser.SelectStmt, schema *storage.Schema, refs []parser.TableRef, multiTable bool, stars map[string]starProjection) []string {
  2428. hasJoin := len(stmt.From) > 0 && stmt.From[0].Join != nil
  2429. names := make([]string, 0, len(stmt.Columns))
  2430. for i, col := range stmt.Columns {
  2431. switch {
  2432. case col.Alias != "":
  2433. names = append(names, col.Alias)
  2434. case col.Star:
  2435. if multiTable || hasJoin {
  2436. for _, ref := range refs {
  2437. if refSchema, err := e.session.GetSchema(ref.Name); err == nil {
  2438. for _, c := range refSchema.Columns {
  2439. names = append(names, c.Name)
  2440. }
  2441. }
  2442. }
  2443. continue
  2444. }
  2445. for _, c := range schema.Columns {
  2446. names = append(names, c.Name)
  2447. }
  2448. case col.TableStar != "":
  2449. for _, c := range stars[strings.ToUpper(col.TableStar)].cols {
  2450. names = append(names, c.Name)
  2451. }
  2452. case col.Expr != nil:
  2453. if ref, ok := col.Expr.(*parser.ColumnRef); ok {
  2454. names = append(names, ref.Column)
  2455. continue
  2456. }
  2457. names = append(names, fmt.Sprintf("column%d", i+1))
  2458. default:
  2459. names = append(names, fmt.Sprintf("column%d", i+1))
  2460. }
  2461. }
  2462. return names
  2463. }
  2464. // resolveTableStar resolves a qualified wildcard (table.*) qualifier to the
  2465. // matching table ref in a FROM clause. It returns the table's schema columns
  2466. // and the key prefix used to look values up in a joined/aliased row (the
  2467. // effective table alias). An unknown qualifier is an error, never a silent
  2468. // fallback to plain column expansion.
  2469. func (e *Executor) resolveTableStar(from []parser.TableRef, qualifier string) ([]storage.Column, string, error) {
  2470. refs := collectAllTableRefs(from)
  2471. for _, ref := range refs {
  2472. if strings.EqualFold(ref.Alias, qualifier) {
  2473. sch, err := e.session.GetSchema(ref.Name)
  2474. if err != nil {
  2475. return nil, "", err
  2476. }
  2477. return sch.Columns, ref.Alias, nil
  2478. }
  2479. }
  2480. for _, ref := range refs {
  2481. if strings.EqualFold(ref.Name, qualifier) {
  2482. sch, err := e.session.GetSchema(ref.Name)
  2483. if err != nil {
  2484. return nil, "", err
  2485. }
  2486. return sch.Columns, ref.Alias, nil
  2487. }
  2488. }
  2489. return nil, "", fmt.Errorf("no such table or alias: %s", qualifier)
  2490. }
  2491. // addTableAlias adds table-qualified names to a row.
  2492. // normalizeRowBySchema converts float64 values in integer-affinity columns to int64.
  2493. // This is needed because JSON deserialization always produces float64 for numbers.
  2494. func normalizeRowBySchema(row storage.Row, schema *storage.Schema) {
  2495. if schema == nil {
  2496. return
  2497. }
  2498. for _, col := range schema.Columns {
  2499. upper := strings.ToUpper(col.Type)
  2500. isInt := strings.Contains(upper, "INT") || upper == "BOOLEAN" || upper == "BOOL"
  2501. if !isInt {
  2502. continue
  2503. }
  2504. if f, ok := row[col.Name].(float64); ok {
  2505. row[col.Name] = int64(f)
  2506. }
  2507. }
  2508. }
  2509. func (e *Executor) addTableAlias(row storage.Row, alias string) storage.Row {
  2510. result := make(storage.Row)
  2511. for k, v := range row {
  2512. result[k] = v
  2513. // Don't add alias to already-qualified names
  2514. if !strings.Contains(k, ".") {
  2515. result[alias+"."+k] = v
  2516. }
  2517. }
  2518. return result
  2519. }
  2520. // isConflictError reports whether an insert failed because of a primary-key or
  2521. // unique-index conflict.
  2522. func isConflictError(err error) bool {
  2523. if err == nil {
  2524. return false
  2525. }
  2526. msg := err.Error()
  2527. return strings.Contains(msg, "duplicate") || strings.Contains(msg, "UNIQUE constraint failed")
  2528. }
  2529. // findConflictRow returns the first row matching the inserted row on the given
  2530. // target columns. A primary-key target uses a point read and a unique-index
  2531. // target uses an indexed lookup; only an unindexed composite target falls back
  2532. // to a scan.
  2533. func (e *Executor) findConflictRow(table string, schema *storage.Schema, row storage.Row, columns []string) (storage.Row, bool, error) {
  2534. if schema.PrimaryKeyTargetMatches(columns) {
  2535. pk, err := schema.PrimaryKeyForRow(row)
  2536. if err != nil {
  2537. // A missing or NULL key component cannot conflict: the insert itself
  2538. // fails with the NOT NULL violation.
  2539. return nil, false, nil
  2540. }
  2541. found, err := e.session.GetByPK(table, pk)
  2542. if err == storage.ErrKeyNotFound {
  2543. return nil, false, nil
  2544. }
  2545. if err != nil {
  2546. return nil, false, err
  2547. }
  2548. return found, true, nil
  2549. }
  2550. indexes, err := e.session.ListTableIndexes(table)
  2551. if err != nil {
  2552. return nil, false, err
  2553. }
  2554. for _, idx := range indexes {
  2555. if !idx.Unique || len(idx.Columns) != len(columns) {
  2556. continue
  2557. }
  2558. matches := true
  2559. for i, col := range columns {
  2560. if !strings.EqualFold(idx.Columns[i].Name, col) {
  2561. matches = false
  2562. break
  2563. }
  2564. }
  2565. if !matches {
  2566. continue
  2567. }
  2568. key, err := e.table.IndexRowKey(idx, row)
  2569. if err != nil {
  2570. return nil, false, err
  2571. }
  2572. rows, err := e.session.SelectByIndexKey(table, idx, key)
  2573. if err != nil {
  2574. return nil, false, err
  2575. }
  2576. if len(rows) == 0 {
  2577. return nil, false, nil
  2578. }
  2579. return rows[0], true, nil
  2580. }
  2581. rows, err := e.session.Select(table, func(existing storage.Row) bool {
  2582. for _, col := range columns {
  2583. ev, eok := lookupRowValue(existing, col)
  2584. cv, cok := lookupRowValue(row, col)
  2585. if !eok || !cok || ev == nil || cv == nil || compare(ev, cv) != 0 {
  2586. return false
  2587. }
  2588. }
  2589. return true
  2590. })
  2591. if err != nil {
  2592. return nil, false, err
  2593. }
  2594. if len(rows) == 0 {
  2595. return nil, false, nil
  2596. }
  2597. return rows[0], true, nil
  2598. }
  2599. // applyUpsert implements ON CONFLICT (target) DO UPDATE SET ... for primary-key
  2600. // and unique-index conflicts, resolving excluded.<col> to the new row.
  2601. func (e *Executor) applyUpsert(table string, schema *storage.Schema, existing, row storage.Row, assignments []parser.Assignment) error {
  2602. context := make(storage.Row)
  2603. for k, v := range existing {
  2604. context[k] = v
  2605. context[table+"."+k] = v
  2606. }
  2607. for k, v := range row {
  2608. context["excluded."+k] = v
  2609. }
  2610. pk, err := schema.PrimaryKeyForRow(existing)
  2611. if err != nil {
  2612. return err
  2613. }
  2614. _, updated, err := e.session.UpdateByPK(table, pk, func(current storage.Row) (storage.Row, error) {
  2615. updates := make(storage.Row)
  2616. merged := make(storage.Row, len(current))
  2617. for k, v := range current {
  2618. merged[k] = v
  2619. }
  2620. for _, assignment := range assignments {
  2621. value, evalErr := e.evalExpr(assignment.Value, context)
  2622. if evalErr != nil {
  2623. return nil, evalErr
  2624. }
  2625. updates[assignment.Column] = value
  2626. merged[assignment.Column] = value
  2627. }
  2628. if normalizeErr := e.normalizeArrayRow(schema, updates); normalizeErr != nil {
  2629. return nil, normalizeErr
  2630. }
  2631. // Recompute STORED generated columns so an upsert keeps them current.
  2632. if err := e.applyGeneratedColumns(schema, merged); err != nil {
  2633. return nil, err
  2634. }
  2635. for _, col := range schema.Columns {
  2636. if col.GeneratedExpr != "" {
  2637. updates[col.Name] = merged[col.Name]
  2638. }
  2639. }
  2640. return updates, nil
  2641. })
  2642. if err != nil {
  2643. return err
  2644. }
  2645. if !updated {
  2646. return fmt.Errorf("ON CONFLICT row disappeared during update")
  2647. }
  2648. return nil
  2649. }
  2650. // executeInsert executes an INSERT statement.
  2651. func (e *Executor) executeInsert(stmt *parser.InsertStmt) (*Result, error) {
  2652. tableName := stmt.Table.Name
  2653. schema, err := e.session.GetSchema(tableName)
  2654. if err != nil {
  2655. return nil, err
  2656. }
  2657. // RETURNING and conflict-clause expressions may subscript array columns.
  2658. e.pushTypeScope(schemaTypeResolver(schema))
  2659. defer e.popTypeScope()
  2660. generated := generatedColumnSet(schema)
  2661. if len(stmt.Columns) > 0 {
  2662. for _, col := range stmt.Columns {
  2663. if generated[strings.ToLower(col)] {
  2664. return nil, fmt.Errorf("cannot INSERT into generated column %s", col)
  2665. }
  2666. }
  2667. }
  2668. // An upsert is applied as an in-place update of the conflicting row, so it
  2669. // cannot move that row to a new primary key. Accepting the assignment would
  2670. // leave the durable row under its old key with the new key values in its
  2671. // body, which makes later full-key reads and updates split the row in two.
  2672. for _, assignment := range stmt.ConflictUpdate {
  2673. if schema.IsPrimaryKeyColumn(assignment.Column) {
  2674. return nil, pgerror.Unsupported(
  2675. "ON CONFLICT DO UPDATE cannot assign primary key column %q of table %s; delete and re-insert the row to change its key",
  2676. assignment.Column, tableName,
  2677. )
  2678. }
  2679. }
  2680. // Defaults are resolved once per statement: expression defaults are
  2681. // evaluated at the statement instant so a multi-row INSERT shares one value,
  2682. // and constant catalog defaults are copied into the candidate row. Resolving
  2683. // both here lets conflict matching and RETURNING see the same key the storage
  2684. // layer will write; storage still applies them as a fallback for rows that
  2685. // reach it another way.
  2686. defaults, err := e.statementDefaults(schema)
  2687. if err != nil {
  2688. return nil, err
  2689. }
  2690. force := stmt.OnConflict == parser.ConflictReplace
  2691. // INSERT ... SELECT: materialise the SELECT result and bulk-insert.
  2692. if stmt.Select != nil {
  2693. sel, err := e.executeSelect(stmt.Select)
  2694. if err != nil {
  2695. return nil, err
  2696. }
  2697. rows := make([]storage.Row, 0, len(sel.Rows))
  2698. for _, selRow := range sel.Rows {
  2699. row := make(storage.Row)
  2700. if len(stmt.Columns) > 0 {
  2701. for i, col := range stmt.Columns {
  2702. if i < len(selRow) {
  2703. row[col] = selRow[i]
  2704. }
  2705. }
  2706. } else {
  2707. // Generated columns are not writable, so they are skipped when
  2708. // values are mapped positionally to the table's columns.
  2709. dst := 0
  2710. for _, col := range schema.Columns {
  2711. if generated[strings.ToLower(col.Name)] {
  2712. continue
  2713. }
  2714. if dst < len(selRow) {
  2715. row[col.Name] = selRow[dst]
  2716. }
  2717. dst++
  2718. }
  2719. }
  2720. applyRowDefaults(row, defaults)
  2721. if len(generated) > 0 {
  2722. if err := e.ensureGeneratedRowID(tableName, schema, row); err != nil {
  2723. return nil, err
  2724. }
  2725. }
  2726. if err := e.applyGeneratedColumns(schema, row); err != nil {
  2727. return nil, err
  2728. }
  2729. rows = append(rows, row)
  2730. }
  2731. count := 0
  2732. var lastRowID int64
  2733. var didInsert bool
  2734. var affected []storage.Row
  2735. err = e.runDMLAtomicForce(tableName, force || len(rows) > 1, func() error {
  2736. for _, row := range rows {
  2737. rid, inserted, wasAffected, stored, ierr := e.insertOneRow(tableName, schema, row, stmt, len(stmt.Returning) > 0)
  2738. if ierr != nil {
  2739. return ierr
  2740. }
  2741. if inserted {
  2742. lastRowID = rid
  2743. didInsert = true
  2744. }
  2745. if wasAffected {
  2746. count++
  2747. if len(stmt.Returning) > 0 && stored != nil {
  2748. affected = append(affected, stored)
  2749. }
  2750. }
  2751. }
  2752. return nil
  2753. })
  2754. if err != nil {
  2755. return nil, err
  2756. }
  2757. return e.finishDML("INSERT", count, lastRowID, didInsert, affected, stmt.Returning, schema)
  2758. }
  2759. count := 0
  2760. var lastRowID int64
  2761. var didInsert bool
  2762. var affected []storage.Row
  2763. err = e.runDMLAtomicForce(tableName, force || len(stmt.Values) > 1, func() error {
  2764. for _, values := range stmt.Values {
  2765. row := make(storage.Row)
  2766. if len(stmt.Columns) > 0 {
  2767. // Named columns
  2768. for i, col := range stmt.Columns {
  2769. if i < len(values) {
  2770. val, err := e.evalExpr(values[i], nil)
  2771. if err != nil {
  2772. return err
  2773. }
  2774. row[col] = val
  2775. }
  2776. }
  2777. } else {
  2778. // Positional values map to the table's non-generated columns.
  2779. dst := 0
  2780. for _, col := range schema.Columns {
  2781. if generated[strings.ToLower(col.Name)] {
  2782. continue
  2783. }
  2784. if dst < len(values) {
  2785. val, err := e.evalExpr(values[dst], nil)
  2786. if err != nil {
  2787. return err
  2788. }
  2789. row[col.Name] = val
  2790. }
  2791. dst++
  2792. }
  2793. }
  2794. applyRowDefaults(row, defaults)
  2795. if len(generated) > 0 {
  2796. if err := e.ensureGeneratedRowID(tableName, schema, row); err != nil {
  2797. return err
  2798. }
  2799. }
  2800. if err := e.applyGeneratedColumns(schema, row); err != nil {
  2801. return err
  2802. }
  2803. rowID, inserted, wasAffected, stored, ierr := e.insertOneRow(tableName, schema, row, stmt, len(stmt.Returning) > 0)
  2804. if ierr != nil {
  2805. return ierr
  2806. }
  2807. if inserted {
  2808. lastRowID = rowID
  2809. didInsert = true
  2810. }
  2811. if wasAffected {
  2812. count++
  2813. if len(stmt.Returning) > 0 && stored != nil {
  2814. affected = append(affected, stored)
  2815. }
  2816. }
  2817. }
  2818. return nil
  2819. })
  2820. if err != nil {
  2821. return nil, err
  2822. }
  2823. return e.finishDML("INSERT", count, lastRowID, didInsert, affected, stmt.Returning, schema)
  2824. }
  2825. // insertOneRow applies ON CONFLICT upsert/ignore/replace rules and then writes a
  2826. // single fully-resolved row (generated columns already computed). It reports
  2827. // whether a new row was inserted (for last_insert_rowid), whether any row was
  2828. // affected (inserted or upsert-updated), and the stored row when requested for
  2829. // RETURNING. An ON CONFLICT DO UPDATE returns the merged existing row, not the
  2830. // candidate, so RETURNING and unique-target upserts observe the real row.
  2831. func (e *Executor) insertOneRow(tableName string, schema *storage.Schema, row storage.Row, stmt *parser.InsertStmt, wantStored bool) (int64, bool, bool, storage.Row, error) {
  2832. // Canonicalize array column values once, before conflict matching reads
  2833. // them and before storage encodes them.
  2834. if err := e.normalizeArrayRow(schema, row); err != nil {
  2835. return 0, false, false, nil, err
  2836. }
  2837. if stmt.OnConflict == parser.ConflictIgnore || (stmt.ConflictDoNothing && len(stmt.ConflictTarget) == 0) {
  2838. conflict, err := e.hasAnyInsertConflict(tableName, schema, row)
  2839. if err != nil {
  2840. return 0, false, false, nil, err
  2841. }
  2842. if conflict {
  2843. return 0, false, false, nil, nil
  2844. }
  2845. }
  2846. if stmt.ConflictDoNothing || len(stmt.ConflictUpdate) > 0 {
  2847. columns := stmt.ConflictTarget
  2848. if len(columns) == 0 && !schema.UsesSyntheticRowID() {
  2849. columns = schema.PrimaryKeyList()
  2850. }
  2851. if len(columns) > 0 {
  2852. existing, found, err := e.findConflictRow(tableName, schema, row, columns)
  2853. if err != nil {
  2854. return 0, false, false, nil, err
  2855. }
  2856. if found {
  2857. if stmt.ConflictDoNothing {
  2858. return 0, false, false, nil, nil
  2859. }
  2860. generated := generatedColumnSet(schema)
  2861. for _, assignment := range stmt.ConflictUpdate {
  2862. if generated[strings.ToLower(assignment.Column)] {
  2863. return 0, false, false, nil, fmt.Errorf("cannot UPDATE generated column %s", assignment.Column)
  2864. }
  2865. }
  2866. existingPK, _ := schema.PrimaryKeyForRow(existing)
  2867. if err := e.applyUpsert(tableName, schema, existing, row, stmt.ConflictUpdate); err != nil {
  2868. return 0, false, false, nil, err
  2869. }
  2870. var stored storage.Row
  2871. if wantStored {
  2872. stored = e.fetchByPK(tableName, existingPK)
  2873. }
  2874. return 0, false, true, stored, nil
  2875. }
  2876. }
  2877. }
  2878. // ON CONFLICT REPLACE (statement-level or per-index) removes conflicting
  2879. // rows before the insert so a unique-index conflict cannot surface later at
  2880. // commit. Plain inserts have no REPLACE matchers and skip the lookup.
  2881. if err := e.resolveInsertConflicts(tableName, schema, row, stmt.OnConflict == parser.ConflictReplace); err != nil {
  2882. return 0, false, false, nil, err
  2883. }
  2884. rowID, err := e.session.InsertWithRowID(tableName, row)
  2885. if err != nil {
  2886. // A unique-index conflict may only surface at transaction commit, so
  2887. // replacing is resolved up front; this retry covers a plain primary-key
  2888. // duplicate that appeared without a matching REPLACE matcher.
  2889. if isConflictError(err) {
  2890. switch stmt.OnConflict {
  2891. case parser.ConflictIgnore:
  2892. return 0, false, false, nil, nil
  2893. case parser.ConflictReplace:
  2894. pk, pkErr := schema.PrimaryKeyForRow(row)
  2895. if pkErr == nil {
  2896. if _, deleted, delErr := e.session.DeleteByPK(tableName, pk); delErr == nil && deleted {
  2897. replacedID, replaceErr := e.session.InsertWithRowID(tableName, row)
  2898. if replaceErr != nil {
  2899. return 0, false, false, nil, replaceErr
  2900. }
  2901. return replacedID, true, true, e.fetchIfRequested(tableName, schema, row, wantStored), nil
  2902. }
  2903. }
  2904. return 0, false, false, nil, err
  2905. default:
  2906. return 0, false, false, nil, err
  2907. }
  2908. }
  2909. return 0, false, false, nil, err
  2910. }
  2911. return rowID, true, true, e.fetchIfRequested(tableName, schema, row, wantStored), nil
  2912. }
  2913. // fetchIfRequested reads back the stored row only when a RETURNING projection
  2914. // needs it, avoiding an extra point read for ordinary inserts.
  2915. func (e *Executor) fetchIfRequested(tableName string, schema *storage.Schema, row storage.Row, want bool) storage.Row {
  2916. if !want {
  2917. return nil
  2918. }
  2919. pk, err := schema.PrimaryKeyForRow(row)
  2920. if err != nil {
  2921. return row
  2922. }
  2923. return e.fetchByPK(tableName, pk)
  2924. }
  2925. // fetchByPK reads a stored row, falling back to nil on a read error; RETURNING
  2926. // then simply omits that row rather than failing the whole statement.
  2927. func (e *Executor) fetchByPK(tableName, pk string) storage.Row {
  2928. stored, err := e.session.GetByPK(tableName, pk)
  2929. if err != nil {
  2930. return nil
  2931. }
  2932. return stored
  2933. }
  2934. // finishDML records session change counters and builds the statement result,
  2935. // attaching RETURNING rows when the statement requested them. last_insert_rowid
  2936. // is only advanced when a new row was actually inserted, so UPDATE, DELETE, and
  2937. // an ON CONFLICT DO UPDATE do not reset the session value.
  2938. func (e *Executor) finishDML(tag string, count int, lastRowID int64, inserted bool, affected []storage.Row, returning []parser.SelectColumn, schema *storage.Schema) (*Result, error) {
  2939. e.recordChanges(int64(count))
  2940. if inserted {
  2941. e.lastInsertRowID = lastRowID
  2942. }
  2943. if len(returning) > 0 {
  2944. result, err := e.returningResult(returning, schema, affected)
  2945. if err != nil {
  2946. return nil, err
  2947. }
  2948. result.CommandTag = tag
  2949. result.RowsAffected = int64(count)
  2950. result.LastInsertID = e.lastInsertRowID
  2951. return result, nil
  2952. }
  2953. result := NewResult(tag)
  2954. result.SetRowCount(count)
  2955. result.SetLastInsertID(e.lastInsertRowID)
  2956. return result, nil
  2957. }
  2958. // recordChanges updates the session-local changes()/total_changes() state after
  2959. // a successful INSERT/UPDATE/DELETE. total_changes() is a monotonic counter of
  2960. // every completed DML statement (SQLite semantics): it is incremented even when
  2961. // the change is later undone by ROLLBACK or ROLLBACK TO, and is never decremented.
  2962. func (e *Executor) recordChanges(affected int64) {
  2963. e.changes = affected
  2964. e.totalChanges += affected
  2965. }
  2966. // runDMLAtomic runs apply, staging the DML in an implicit transaction when the
  2967. // target table carries a UNIQUE index and no explicit transaction is open, so a
  2968. // statement that fails partway (e.g. a multi-row UPDATE/INSERT that hits a unique
  2969. // violation after earlier rows staged) leaves no durable effects — matching
  2970. // SQLite's statement-level atomicity. It commits on success and rolls back on any
  2971. // error. When already in an explicit transaction, apply runs directly and the
  2972. // surrounding COMMIT/ROLLBACK governs durability.
  2973. func (e *Executor) runDMLAtomic(tableName string, apply func() error) error {
  2974. return e.runDMLAtomicForce(tableName, false, apply)
  2975. }
  2976. // runDMLAtomicForce is runDMLAtomic with an override that forces an implicit
  2977. // transaction even when the table has no UNIQUE index. INSERT OR REPLACE needs
  2978. // it because a primary-key replacement must delete and insert atomically.
  2979. func (e *Executor) runDMLAtomicForce(tableName string, force bool, apply func() error) error {
  2980. if e.session.InTx() {
  2981. pos := e.session.Snapshot()
  2982. if err := apply(); err != nil {
  2983. e.session.RollbackTo(pos)
  2984. return err
  2985. }
  2986. return nil
  2987. }
  2988. uniq, err := e.table.HasUniqueIndex(tableName)
  2989. if err != nil {
  2990. return err
  2991. }
  2992. if !uniq && !force {
  2993. return apply()
  2994. }
  2995. if err := e.session.Begin(); err != nil {
  2996. return err
  2997. }
  2998. if err := apply(); err != nil {
  2999. _ = e.session.Rollback()
  3000. return err
  3001. }
  3002. return e.session.Commit()
  3003. }
  3004. // executeAtomicMutation includes evaluation and RETURNING in the statement's
  3005. // atomic boundary. Nested calls use mutation-log savepoints, not nested commits.
  3006. func (e *Executor) executeAtomicMutation(apply func() (*Result, error)) (*Result, error) {
  3007. owned := !e.session.InTx()
  3008. if owned {
  3009. if err := e.session.Begin(); err != nil {
  3010. return nil, err
  3011. }
  3012. }
  3013. pos := e.session.Snapshot()
  3014. changes, total, last := e.changes, e.totalChanges, e.lastInsertRowID
  3015. result, err := apply()
  3016. if err == nil && owned {
  3017. var lsn uint64
  3018. lsn, err = e.session.CommitWithLSN()
  3019. if err == nil {
  3020. result.LSN = lsn
  3021. }
  3022. }
  3023. if err != nil {
  3024. if owned {
  3025. _ = e.session.Rollback()
  3026. } else {
  3027. e.session.RollbackTo(pos)
  3028. }
  3029. e.changes, e.totalChanges, e.lastInsertRowID = changes, total, last
  3030. return nil, err
  3031. }
  3032. return result, nil
  3033. }
  3034. func (e *Executor) isPointMutation(table string, where parser.Expr, assignments []parser.Assignment) bool {
  3035. column, value, equality := e.extractIndexableCondition(where)
  3036. if !equality || !safePrimaryKeyLiteral(value) {
  3037. return false
  3038. }
  3039. schema, err := e.session.GetSchema(table)
  3040. if err != nil || !schema.IsSingleColumnPrimaryKey() || !strings.EqualFold(column, schema.PrimaryKey) {
  3041. return false
  3042. }
  3043. for _, assignment := range assignments {
  3044. if schema.IsPrimaryKeyColumn(assignment.Column) {
  3045. return false
  3046. }
  3047. }
  3048. return true
  3049. }
  3050. func containsFold(values []string, target string) bool {
  3051. for _, value := range values {
  3052. if strings.EqualFold(value, target) {
  3053. return true
  3054. }
  3055. }
  3056. return false
  3057. }
  3058. // primeSubqueries pre-executes non-correlated subqueries referenced by a
  3059. // statement expression and stores their results in the per-query subquery cache.
  3060. // It runs before the storage session acquires its lock for a scan-based
  3061. // UPDATE/DELETE. Without this, evaluating a predicate such as
  3062. // "WHERE id IN (SELECT ...)" invokes the session recursively while the session
  3063. // lock is held, which deadlocks. The cache is only consulted when there is no
  3064. // outer row (see evalInExpr), so priming is limited to that same non-correlated
  3065. // case.
  3066. func (e *Executor) primeSubqueries(expr parser.Expr) {
  3067. if expr == nil || e.subqueryCache == nil || e.outerRow != nil {
  3068. return
  3069. }
  3070. prime := func(sub *parser.SelectStmt) {
  3071. if sub == nil {
  3072. return
  3073. }
  3074. if _, ok := e.subqueryCache[sub]; ok {
  3075. return
  3076. }
  3077. if result, err := e.executeSelect(sub); err == nil {
  3078. e.subqueryCache[sub] = result
  3079. }
  3080. }
  3081. var walk func(parser.Expr)
  3082. walk = func(x parser.Expr) {
  3083. if x == nil {
  3084. return
  3085. }
  3086. switch n := x.(type) {
  3087. case *parser.InExpr:
  3088. prime(n.Subquery)
  3089. walk(n.Left)
  3090. for _, v := range n.Values {
  3091. walk(v)
  3092. }
  3093. case *parser.SubqueryExpr:
  3094. prime(n.Query)
  3095. case *parser.ExistsExpr:
  3096. prime(n.Subquery)
  3097. case *parser.BinaryExpr:
  3098. walk(n.Left)
  3099. walk(n.Right)
  3100. case *parser.UnaryExpr:
  3101. walk(n.Operand)
  3102. case *parser.BetweenExpr:
  3103. walk(n.Left)
  3104. walk(n.Low)
  3105. walk(n.High)
  3106. case *parser.LikeExpr:
  3107. walk(n.Left)
  3108. walk(n.Pattern)
  3109. walk(n.Escape)
  3110. case *parser.IsNullExpr:
  3111. walk(n.Left)
  3112. case *parser.IsDistinctExpr:
  3113. walk(n.Left)
  3114. walk(n.Right)
  3115. case *parser.CaseExpr:
  3116. walk(n.Operand)
  3117. for _, w := range n.Whens {
  3118. walk(w.Condition)
  3119. walk(w.Result)
  3120. }
  3121. walk(n.Else)
  3122. case *parser.FunctionCall:
  3123. for _, a := range n.Args {
  3124. walk(a)
  3125. }
  3126. case *parser.ParenExpr:
  3127. walk(n.Expr)
  3128. case *parser.CastExpr:
  3129. walk(n.Expr)
  3130. case *parser.ArrayExpr:
  3131. for _, element := range n.Elements {
  3132. walk(element)
  3133. }
  3134. case *parser.SubscriptExpr:
  3135. walk(n.Expr)
  3136. walk(n.Index)
  3137. case *parser.AnyAllExpr:
  3138. walk(n.Left)
  3139. walk(n.Array)
  3140. }
  3141. }
  3142. walk(expr)
  3143. }
  3144. // executeUpdate executes an UPDATE statement.
  3145. func (e *Executor) executeUpdate(stmt *parser.UpdateStmt) (*Result, error) {
  3146. tableName := stmt.Table.Name
  3147. schema, err := e.session.GetSchema(tableName)
  3148. if err != nil {
  3149. return nil, err
  3150. }
  3151. // SET and WHERE expressions may subscript array columns; expose the target
  3152. // table's declared types for the duration of the statement.
  3153. e.pushTypeScope(schemaTypeResolver(schema))
  3154. defer e.popTypeScope()
  3155. generated := generatedColumnSet(schema)
  3156. for _, assign := range stmt.Set {
  3157. if generated[strings.ToLower(assign.Column)] {
  3158. return nil, fmt.Errorf("cannot UPDATE generated column %s", assign.Column)
  3159. }
  3160. }
  3161. // UPDATE ... FROM joins the target against materialized source rows. It is
  3162. // handled separately because SET expressions and WHERE may reference both
  3163. // the target and the source row.
  3164. if len(stmt.From) > 0 {
  3165. return e.executeUpdateFrom(stmt, schema)
  3166. }
  3167. // Keep predicate errors inside the statement rollback boundary.
  3168. var filterErr error
  3169. var filter func(storage.Row) bool
  3170. if stmt.Where != nil {
  3171. filter = func(row storage.Row) bool {
  3172. val, err := e.evalExpr(stmt.Where, row)
  3173. if err != nil {
  3174. filterErr = err
  3175. return false
  3176. }
  3177. return toBool(val)
  3178. }
  3179. }
  3180. // Use UpdateFunc to evaluate expressions per-row (supports self-referencing like balance = balance + 100).
  3181. // Generated columns are recomputed from the post-assignment row and written
  3182. // back so STORED values stay consistent.
  3183. updateFn := func(row storage.Row) (storage.Row, error) {
  3184. updates := make(storage.Row)
  3185. merged := make(storage.Row, len(row))
  3186. for k, v := range row {
  3187. merged[k] = v
  3188. }
  3189. for _, assign := range stmt.Set {
  3190. val, err := e.evalExpr(assign.Value, row)
  3191. if err != nil {
  3192. return nil, err
  3193. }
  3194. updates[assign.Column] = val
  3195. merged[assign.Column] = val
  3196. }
  3197. if err := e.normalizeArrayRow(schema, updates); err != nil {
  3198. return nil, err
  3199. }
  3200. if err := e.applyGeneratedColumns(schema, merged); err != nil {
  3201. return nil, err
  3202. }
  3203. for _, col := range schema.Columns {
  3204. if col.GeneratedExpr != "" {
  3205. updates[col.Name] = merged[col.Name]
  3206. }
  3207. }
  3208. return updates, nil
  3209. }
  3210. // Pre-evaluate subqueries in the predicate and assignments before any
  3211. // session read takes the lock. A correlated subquery evaluated during the
  3212. // locked scan would re-enter the session lock and deadlock.
  3213. e.primeSubqueries(stmt.Where)
  3214. for _, assign := range stmt.Set {
  3215. e.primeSubqueries(assign.Value)
  3216. }
  3217. if stmt.Where != nil {
  3218. column, value, equality := e.extractIndexableCondition(stmt.Where)
  3219. updatesPrimaryKey := false
  3220. for _, assignment := range stmt.Set {
  3221. if schema.IsPrimaryKeyColumn(assignment.Column) {
  3222. updatesPrimaryKey = true
  3223. break
  3224. }
  3225. }
  3226. if equality && safePrimaryKeyLiteral(value) && schema.IsSingleColumnPrimaryKey() && strings.EqualFold(column, schema.PrimaryKey) && !updatesPrimaryKey {
  3227. pk := fmt.Sprintf("%v", value)
  3228. _, updated, err := e.session.UpdateByPK(tableName, pk, updateFn)
  3229. if err != nil {
  3230. return nil, err
  3231. }
  3232. count := 0
  3233. var affected []storage.Row
  3234. if updated {
  3235. count = 1
  3236. if len(stmt.Returning) > 0 {
  3237. affected = append(affected, e.fetchByPK(tableName, pk))
  3238. }
  3239. }
  3240. return e.finishDML("UPDATE", count, 0, false, affected, stmt.Returning, schema)
  3241. }
  3242. }
  3243. // When RETURNING is requested, capture the matched rows and compute the
  3244. // post-update primary key for each, so a primary-key UPDATE returns the row
  3245. // under its NEW key rather than the old one.
  3246. var returningPKs []string
  3247. if len(stmt.Returning) > 0 {
  3248. matched, serr := e.session.Select(tableName, filter)
  3249. if serr != nil {
  3250. return nil, serr
  3251. }
  3252. for _, r := range matched {
  3253. merged, merr := applyUpdateRow(updateFn, r, schema)
  3254. if merr != nil {
  3255. return nil, merr
  3256. }
  3257. key, keyErr := schema.PrimaryKeyForRow(merged)
  3258. if keyErr != nil {
  3259. key, _ = schema.PrimaryKeyForRow(r)
  3260. }
  3261. returningPKs = append(returningPKs, key)
  3262. }
  3263. }
  3264. count := 0
  3265. err = e.runDMLAtomic(tableName, func() error {
  3266. n, err := e.session.UpdateFunc(tableName, updateFn, filter)
  3267. if err != nil {
  3268. return err
  3269. }
  3270. if filterErr != nil {
  3271. return filterErr
  3272. }
  3273. count = n
  3274. return nil
  3275. })
  3276. if err != nil {
  3277. return nil, err
  3278. }
  3279. var affected []storage.Row
  3280. if len(stmt.Returning) > 0 {
  3281. for _, pk := range returningPKs {
  3282. if stored := e.fetchByPK(tableName, pk); stored != nil {
  3283. affected = append(affected, stored)
  3284. }
  3285. }
  3286. }
  3287. return e.finishDML("UPDATE", count, 0, false, affected, stmt.Returning, schema)
  3288. }
  3289. // applyUpdateRow runs an update callback against a row and returns the fully
  3290. // merged post-update row (including generated columns). It has no side effects;
  3291. // callers use it to predict the new primary key for RETURNING.
  3292. func applyUpdateRow(updateFn func(storage.Row) (storage.Row, error), row storage.Row, schema *storage.Schema) (storage.Row, error) {
  3293. updates, err := updateFn(row)
  3294. if err != nil {
  3295. return nil, err
  3296. }
  3297. merged := make(storage.Row, len(row))
  3298. for k, v := range row {
  3299. merged[k] = v
  3300. }
  3301. for k, v := range updates {
  3302. target := k
  3303. for existing := range merged {
  3304. if strings.EqualFold(existing, k) {
  3305. target = existing
  3306. break
  3307. }
  3308. }
  3309. if target == k {
  3310. for _, col := range schema.Columns {
  3311. if strings.EqualFold(col.Name, k) {
  3312. target = col.Name
  3313. break
  3314. }
  3315. }
  3316. }
  3317. merged[target] = v
  3318. }
  3319. return merged, nil
  3320. }
  3321. // executeUpdateFrom implements UPDATE ... FROM. It materializes the FROM sources
  3322. // once, finds each target row's first matching source row, evaluates SET against
  3323. // the combined context, and applies the changes atomically.
  3324. func (e *Executor) executeUpdateFrom(stmt *parser.UpdateStmt, schema *storage.Schema) (*Result, error) {
  3325. tableName := stmt.Table.Name
  3326. e.pushTypeScope(e.snapshotTypeResolver(stmt.From))
  3327. defer e.popTypeScope()
  3328. sources, err := e.materializeFrom(stmt.From)
  3329. if err != nil {
  3330. return nil, err
  3331. }
  3332. e.primeSubqueries(stmt.Where)
  3333. for _, assign := range stmt.Set {
  3334. e.primeSubqueries(assign.Value)
  3335. }
  3336. targets, err := e.session.Select(tableName, nil)
  3337. if err != nil {
  3338. return nil, err
  3339. }
  3340. type updateFromPlan struct {
  3341. oldPK string
  3342. row storage.Row
  3343. }
  3344. var plans []updateFromPlan
  3345. for _, target := range targets {
  3346. var matched storage.Row
  3347. for _, source := range sources {
  3348. combined := combineUpdateFrom(tableName, target, source)
  3349. val, err := e.evalExpr(stmt.Where, combined)
  3350. if err != nil {
  3351. return nil, err
  3352. }
  3353. if toBool(val) {
  3354. matched = source
  3355. break
  3356. }
  3357. }
  3358. if matched == nil {
  3359. continue
  3360. }
  3361. combined := combineUpdateFrom(tableName, target, matched)
  3362. row := make(storage.Row, len(target))
  3363. for k, v := range target {
  3364. row[k] = v
  3365. }
  3366. for _, assign := range stmt.Set {
  3367. val, err := e.evalExpr(assign.Value, combined)
  3368. if err != nil {
  3369. return nil, err
  3370. }
  3371. row[assign.Column] = val
  3372. }
  3373. if err := e.normalizeArrayRow(schema, row); err != nil {
  3374. return nil, err
  3375. }
  3376. if err := e.applyGeneratedColumns(schema, row); err != nil {
  3377. return nil, err
  3378. }
  3379. oldPK, err := schema.PrimaryKeyForRow(target)
  3380. if err != nil {
  3381. return nil, err
  3382. }
  3383. plans = append(plans, updateFromPlan{
  3384. oldPK: oldPK,
  3385. row: row,
  3386. })
  3387. }
  3388. count := 0
  3389. var affected []storage.Row
  3390. err = e.runDMLAtomicForce(tableName, true, func() error {
  3391. for _, plan := range plans {
  3392. newPK, newPKErr := schema.PrimaryKeyForRow(plan.row)
  3393. if newPKErr != nil {
  3394. return newPKErr
  3395. }
  3396. // Apply the whole post-update image through one update so a primary-key
  3397. // move is a real UPDATE: the session stages the key move (with the
  3398. // duplicate check) and fires ON UPDATE actions. Implementing the move as
  3399. // DELETE + INSERT would fire ON DELETE actions instead and drop children.
  3400. updates := make(storage.Row, len(schema.Columns))
  3401. for _, col := range schema.Columns {
  3402. if v, ok := lookupRowValue(plan.row, col.Name); ok {
  3403. updates[col.Name] = v
  3404. }
  3405. }
  3406. _, updated, uerr := e.session.UpdateByPK(tableName, plan.oldPK, func(storage.Row) (storage.Row, error) {
  3407. return updates, nil
  3408. })
  3409. if uerr != nil {
  3410. return uerr
  3411. }
  3412. if !updated {
  3413. continue
  3414. }
  3415. count++
  3416. if len(stmt.Returning) > 0 {
  3417. if stored := e.fetchByPK(tableName, newPK); stored != nil {
  3418. affected = append(affected, stored)
  3419. }
  3420. }
  3421. }
  3422. return nil
  3423. })
  3424. if err != nil {
  3425. return nil, err
  3426. }
  3427. return e.finishDML("UPDATE", count, 0, false, affected, stmt.Returning, schema)
  3428. }
  3429. // combineUpdateFrom builds the evaluation context for UPDATE ... FROM: the
  3430. // target row (plain and table-qualified) overlaid with one source row (plain and
  3431. // alias-qualified).
  3432. func combineUpdateFrom(tableName string, target, source storage.Row) storage.Row {
  3433. combined := make(storage.Row, len(target)*2+len(source))
  3434. for k, v := range target {
  3435. combined[k] = v
  3436. if !strings.Contains(k, ".") {
  3437. combined[tableName+"."+k] = v
  3438. }
  3439. }
  3440. for k, v := range source {
  3441. combined[k] = v
  3442. }
  3443. return combined
  3444. }
  3445. // materializeTableRef materializes a single FROM entry (table or derived table)
  3446. // into rows, adding the alias prefix when one is present.
  3447. func (e *Executor) materializeTableRef(ref parser.TableRef) ([]storage.Row, error) {
  3448. alias := ref.Alias
  3449. if ref.Subquery != nil {
  3450. if alias == "" {
  3451. alias = ref.Name
  3452. }
  3453. res, err := e.executeSelect(ref.Subquery)
  3454. if err != nil {
  3455. return nil, err
  3456. }
  3457. rows := make([]storage.Row, 0, len(res.Rows))
  3458. for _, vals := range res.Rows {
  3459. row := make(storage.Row, len(res.Columns))
  3460. for i, name := range res.Columns {
  3461. if i < len(vals) {
  3462. row[name] = vals[i]
  3463. }
  3464. }
  3465. rows = append(rows, row)
  3466. }
  3467. if alias != "" {
  3468. for i := range rows {
  3469. rows[i] = e.addTableAlias(rows[i], alias)
  3470. }
  3471. }
  3472. return rows, nil
  3473. }
  3474. rows, err := e.session.Select(ref.Name, nil)
  3475. if err != nil {
  3476. return nil, err
  3477. }
  3478. if alias == "" {
  3479. alias = ref.Name
  3480. }
  3481. if alias != "" {
  3482. for i := range rows {
  3483. rows[i] = e.addTableAlias(rows[i], alias)
  3484. }
  3485. }
  3486. return rows, nil
  3487. }
  3488. // materializeFrom materializes the full FROM list as a cross product, honoring
  3489. // each entry's JOIN chain.
  3490. func (e *Executor) materializeFrom(from []parser.TableRef) ([]storage.Row, error) {
  3491. if len(from) == 0 {
  3492. return nil, nil
  3493. }
  3494. rows, err := e.materializeTableRef(from[0])
  3495. if err != nil {
  3496. return nil, err
  3497. }
  3498. if from[0].Join != nil {
  3499. rows, err = e.executeJoins(from[0], rows)
  3500. if err != nil {
  3501. return nil, err
  3502. }
  3503. }
  3504. for _, ref := range from[1:] {
  3505. right, err := e.materializeTableRef(ref)
  3506. if err != nil {
  3507. return nil, err
  3508. }
  3509. if ref.Join != nil {
  3510. right, err = e.executeJoins(ref, right)
  3511. if err != nil {
  3512. return nil, err
  3513. }
  3514. }
  3515. merged := make([]storage.Row, 0, len(rows)*len(right))
  3516. for _, l := range rows {
  3517. for _, r := range right {
  3518. combined := make(storage.Row, len(l)+len(r))
  3519. for k, v := range l {
  3520. combined[k] = v
  3521. }
  3522. for k, v := range r {
  3523. combined[k] = v
  3524. }
  3525. merged = append(merged, combined)
  3526. }
  3527. }
  3528. rows = merged
  3529. }
  3530. return rows, nil
  3531. }
  3532. // executeDelete executes a DELETE statement.
  3533. func (e *Executor) executeDelete(stmt *parser.DeleteStmt) (*Result, error) {
  3534. tableName := stmt.Table.Name
  3535. schema, err := e.session.GetSchema(tableName)
  3536. if err != nil {
  3537. return nil, err
  3538. }
  3539. e.pushTypeScope(schemaTypeResolver(schema))
  3540. defer e.popTypeScope()
  3541. var filterErr error
  3542. var filter func(storage.Row) bool
  3543. if stmt.Where != nil {
  3544. filter = func(row storage.Row) bool {
  3545. val, err := e.evalExpr(stmt.Where, row)
  3546. if err != nil {
  3547. filterErr = err
  3548. return false
  3549. }
  3550. return toBool(val)
  3551. }
  3552. }
  3553. // Pre-evaluate subqueries in the predicate before any session read takes
  3554. // the lock. Evaluating a correlated subquery during the locked scan would
  3555. // re-enter the session lock and deadlock.
  3556. e.primeSubqueries(stmt.Where)
  3557. if stmt.Where != nil {
  3558. column, value, equality := e.extractIndexableCondition(stmt.Where)
  3559. if equality && safePrimaryKeyLiteral(value) && schema.IsSingleColumnPrimaryKey() && strings.EqualFold(column, schema.PrimaryKey) {
  3560. deletedRow, deleted, err := e.session.DeleteByPK(tableName, fmt.Sprintf("%v", value))
  3561. if err != nil {
  3562. return nil, err
  3563. }
  3564. count := 0
  3565. var affected []storage.Row
  3566. if deleted {
  3567. count = 1
  3568. if len(stmt.Returning) > 0 && deletedRow != nil {
  3569. affected = append(affected, deletedRow)
  3570. }
  3571. }
  3572. return e.finishDML("DELETE", count, 0, false, affected, stmt.Returning, schema)
  3573. }
  3574. }
  3575. // Capture the rows that will be deleted so RETURNING can project the
  3576. // pre-delete values (SQLite/PostgreSQL semantics).
  3577. var affected []storage.Row
  3578. if len(stmt.Returning) > 0 {
  3579. matched, serr := e.session.Select(tableName, filter)
  3580. if serr != nil {
  3581. return nil, serr
  3582. }
  3583. affected = append(affected, matched...)
  3584. }
  3585. count, err := e.session.Delete(tableName, filter)
  3586. if err != nil {
  3587. return nil, err
  3588. }
  3589. if filterErr != nil {
  3590. return nil, filterErr
  3591. }
  3592. return e.finishDML("DELETE", count, 0, false, affected, stmt.Returning, schema)
  3593. }
  3594. // executeCreateTable executes a CREATE TABLE statement.
  3595. func (e *Executor) executeCreateTable(stmt *parser.CreateTableStmt) (*Result, error) {
  3596. // Check if exists
  3597. if e.session.TableExists(stmt.Table.Name) {
  3598. if stmt.IfNotExists {
  3599. result := NewResult("CREATE TABLE")
  3600. return result, nil
  3601. }
  3602. return nil, fmt.Errorf("table already exists: %s", stmt.Table.Name)
  3603. }
  3604. // Creating a table can add a FOREIGN KEY to the graph. Serialize the DDL
  3605. // with point writes so a concurrent child insert or parent delete cannot
  3606. // validate against a half-published constraint.
  3607. if e.table != nil {
  3608. unlockFK := e.table.LockForeignKeyWriteGate()
  3609. defer unlockFK()
  3610. }
  3611. // Build schema
  3612. schema := &storage.Schema{
  3613. Name: stmt.Table.Name,
  3614. }
  3615. // A column-level PRIMARY KEY is recorded separately so more than one, or a
  3616. // mix with a table-level PRIMARY KEY, is rejected instead of silently
  3617. // choosing one of them.
  3618. var inlinePrimaryKeyColumns []string
  3619. for _, colDef := range stmt.Columns {
  3620. col := storage.Column{
  3621. Name: colDef.Name,
  3622. Type: colDef.Type.SQLTypeName(),
  3623. Nullable: true,
  3624. }
  3625. if colDef.GeneratedExpr != nil {
  3626. if !colDef.GeneratedStored {
  3627. return nil, fmt.Errorf("VIRTUAL generated columns are not supported; declare %s GENERATED ALWAYS AS (...) STORED", colDef.Name)
  3628. }
  3629. text := parser.FormatExpr(colDef.GeneratedExpr)
  3630. if _, err := parseStoredExpr(text); err != nil {
  3631. return nil, err
  3632. }
  3633. col.GeneratedExpr = text
  3634. col.GeneratedStored = true
  3635. }
  3636. for _, constraint := range colDef.Constraints {
  3637. switch constraint.Type {
  3638. case parser.ConstraintPrimaryKey:
  3639. if col.GeneratedExpr != "" {
  3640. return nil, pgerror.Unsupported(
  3641. "generated column %q cannot be part of a PRIMARY KEY",
  3642. col.Name,
  3643. )
  3644. }
  3645. col.PrimaryKey = true
  3646. col.Nullable = false
  3647. inlinePrimaryKeyColumns = append(inlinePrimaryKeyColumns, col.Name)
  3648. case parser.ConstraintNotNull:
  3649. col.Nullable = false
  3650. case parser.ConstraintDefault:
  3651. if constraint.Default != nil {
  3652. val, exprText, err := defaultColumnValue(e, col.Name, constraint.Default)
  3653. if err != nil {
  3654. return nil, err
  3655. }
  3656. val, exprText, err = canonicalArrayDefault(col.Type, val, exprText)
  3657. if err != nil {
  3658. return nil, err
  3659. }
  3660. col.Default = val
  3661. col.DefaultExpr = exprText
  3662. }
  3663. case parser.ConstraintAutoIncrement:
  3664. schema.AutoIncrement = true
  3665. case parser.ConstraintCheck:
  3666. // Collected after every column is known, because a table-level
  3667. // predicate may reference a later column.
  3668. case parser.ConstraintForeignKey:
  3669. // Resolved once every column and the primary key are known, so a
  3670. // self-reference sees this table's final key.
  3671. }
  3672. }
  3673. schema.Columns = append(schema.Columns, col)
  3674. }
  3675. // Handle table-level constraints. CHECK predicates and FOREIGN KEY
  3676. // declarations are persisted and enforced; foreign keys are resolved after
  3677. // every column and the primary key are known.
  3678. var tablePrimaryKeyColumns []string
  3679. for _, constraint := range stmt.Constraints {
  3680. switch constraint.Type {
  3681. case parser.ConstraintPrimaryKey:
  3682. if len(constraint.Columns) == 0 {
  3683. break
  3684. }
  3685. if len(tablePrimaryKeyColumns) > 0 {
  3686. return nil, pgerror.Unsupported(
  3687. "table %s declares more than one PRIMARY KEY; declare exactly one column list",
  3688. stmt.Table.Name,
  3689. )
  3690. }
  3691. if len(inlinePrimaryKeyColumns) > 0 {
  3692. return nil, pgerror.Unsupported(
  3693. "table %s mixes an inline PRIMARY KEY with a table-level PRIMARY KEY; use one form, and list every key column in the table-level PRIMARY KEY (a, b) for a composite key",
  3694. stmt.Table.Name,
  3695. )
  3696. }
  3697. seen := make(map[string]bool, len(constraint.Columns))
  3698. for _, name := range constraint.Columns {
  3699. column, ok := schema.GetColumn(name)
  3700. if !ok {
  3701. return nil, pgerror.Unsupported(
  3702. "PRIMARY KEY column %q does not exist in table %s",
  3703. name, stmt.Table.Name,
  3704. )
  3705. }
  3706. if column.GeneratedExpr != "" {
  3707. return nil, pgerror.Unsupported(
  3708. "generated column %q cannot be part of a PRIMARY KEY",
  3709. column.Name,
  3710. )
  3711. }
  3712. if seen[strings.ToLower(column.Name)] {
  3713. return nil, pgerror.Unsupported(
  3714. "column %q appears more than once in the PRIMARY KEY of table %s",
  3715. column.Name, stmt.Table.Name,
  3716. )
  3717. }
  3718. seen[strings.ToLower(column.Name)] = true
  3719. tablePrimaryKeyColumns = append(tablePrimaryKeyColumns, column.Name)
  3720. }
  3721. case parser.ConstraintCheck:
  3722. // Handled with the column-level predicates once every column is known.
  3723. case parser.ConstraintForeignKey:
  3724. // Resolved with the inline REFERENCES constraints below.
  3725. }
  3726. }
  3727. if len(inlinePrimaryKeyColumns) > 1 {
  3728. return nil, pgerror.Unsupported(
  3729. "table %s declares more than one inline PRIMARY KEY; use a table-level PRIMARY KEY (%s) instead",
  3730. stmt.Table.Name, strings.Join(inlinePrimaryKeyColumns, ", "),
  3731. )
  3732. }
  3733. if len(inlinePrimaryKeyColumns) == 1 {
  3734. // Mirror the catalog's normalization so foreign-key validation below can
  3735. // resolve a self-reference against this table's primary key.
  3736. schema.PrimaryKey = inlinePrimaryKeyColumns[0]
  3737. }
  3738. if len(tablePrimaryKeyColumns) > 0 {
  3739. schema.PrimaryKeyColumns = tablePrimaryKeyColumns
  3740. for i := range schema.Columns {
  3741. if schema.IsPrimaryKeyColumn(schema.Columns[i].Name) {
  3742. schema.Columns[i].PrimaryKey = true
  3743. schema.Columns[i].Nullable = false
  3744. }
  3745. }
  3746. }
  3747. // Translate inline/table UNIQUE constraints (Gogs/GORM style) into the same
  3748. // scan-validated unique Index metadata that explicit CREATE UNIQUE INDEX
  3749. // produces, so both enforcement and the catalog observe them.
  3750. uniqIndexes := e.uniqueConstraintIndexes(stmt)
  3751. // Column references in generated expressions and CHECK predicates must
  3752. // resolve against the new table, so validate them once every column is known.
  3753. for _, colDef := range stmt.Columns {
  3754. if colDef.GeneratedExpr == nil {
  3755. continue
  3756. }
  3757. if err := ValidateIndexColumns(colDef.GeneratedExpr, schema); err != nil {
  3758. return nil, err
  3759. }
  3760. }
  3761. var columnConstraints []parser.ColumnConstraint
  3762. for _, colDef := range stmt.Columns {
  3763. columnConstraints = append(columnConstraints, colDef.Constraints...)
  3764. }
  3765. checks, err := e.tableChecks(schema, columnConstraints, stmt.Constraints)
  3766. if err != nil {
  3767. return nil, err
  3768. }
  3769. schema.Checks = checks
  3770. foreignKeys, err := e.createTableForeignKeys(stmt, schema, uniqIndexes)
  3771. if err != nil {
  3772. return nil, err
  3773. }
  3774. schema.ForeignKeys = foreignKeys
  3775. if err := e.session.CreateTable(schema); err != nil {
  3776. if stmt.IfNotExists && strings.Contains(err.Error(), "table already exists") {
  3777. return NewResult("CREATE TABLE"), nil
  3778. }
  3779. return nil, err
  3780. }
  3781. // Register each materialized unique index. On failure, best-effort cleanup of
  3782. // the table and any indexes already created for it; outside a transaction the
  3783. // statement's DDL is already durable, while inside one the statement savepoint
  3784. // discards it.
  3785. var created []*storage.Index
  3786. for _, idx := range uniqIndexes {
  3787. if err := e.session.CreateIndex(idx); err != nil {
  3788. for _, c := range created {
  3789. e.session.DropIndex(c.Name)
  3790. }
  3791. e.session.DropTable(stmt.Table.Name)
  3792. return nil, err
  3793. }
  3794. created = append(created, idx)
  3795. }
  3796. if err := e.SyncCatalog(); err != nil {
  3797. return nil, err
  3798. }
  3799. result := NewResult("CREATE TABLE")
  3800. return result, nil
  3801. }
  3802. // uniqueConstraintIndexes translates a CREATE TABLE's inline/table UNIQUE
  3803. // constraints into unique Index definitions. Named constraints keep their name;
  3804. // unnamed constraints (column-level UNIQUE, or bare UNIQUE(col,...)) receive a
  3805. // deterministic internal name derived from the table and columns.
  3806. func (e *Executor) uniqueConstraintIndexes(stmt *parser.CreateTableStmt) []*storage.Index {
  3807. var indexes []*storage.Index
  3808. used := make(map[string]bool)
  3809. uniqueName := func(base string, columns []string) string {
  3810. if base == "" {
  3811. base = "uniq_" + strings.ToLower(stmt.Table.Name) + "_" + strings.ToLower(strings.Join(columns, "_"))
  3812. }
  3813. name := base
  3814. for n := 2; used[strings.ToLower(name)]; n++ {
  3815. name = fmt.Sprintf("%s_%d", base, n)
  3816. }
  3817. used[strings.ToLower(name)] = true
  3818. return name
  3819. }
  3820. add := func(name string, columns []string, conflict parser.ConflictAction, hasConflict bool) {
  3821. idx := &storage.Index{Name: uniqueName(name, columns), Table: stmt.Table.Name, Unique: true}
  3822. if hasConflict {
  3823. idx.OnConflict = conflictActionName(conflict)
  3824. }
  3825. for _, c := range columns {
  3826. idx.Columns = append(idx.Columns, storage.IndexColumn{Name: c})
  3827. }
  3828. indexes = append(indexes, idx)
  3829. }
  3830. for _, constraint := range stmt.Constraints {
  3831. if constraint.Type == parser.ConstraintUnique && len(constraint.Columns) > 0 {
  3832. add(constraint.Name, constraint.Columns, constraint.OnConflict, constraint.HasOnConflict)
  3833. }
  3834. }
  3835. for _, colDef := range stmt.Columns {
  3836. for _, constraint := range colDef.Constraints {
  3837. if constraint.Type == parser.ConstraintUnique {
  3838. add("", []string{colDef.Name}, constraint.OnConflict, constraint.HasOnConflict)
  3839. }
  3840. }
  3841. }
  3842. return indexes
  3843. }
  3844. // conflictActionName maps a parsed conflict action to the durable index metadata
  3845. // spelling (empty for the default ABORT).
  3846. func conflictActionName(action parser.ConflictAction) string {
  3847. switch action {
  3848. case parser.ConflictReplace:
  3849. return "REPLACE"
  3850. case parser.ConflictIgnore:
  3851. return "IGNORE"
  3852. case parser.ConflictFail:
  3853. return "FAIL"
  3854. case parser.ConflictRollback:
  3855. return "ROLLBACK"
  3856. default:
  3857. return "ABORT"
  3858. }
  3859. }
  3860. // executeDropTable executes a DROP TABLE statement.
  3861. func (e *Executor) executeDropTable(stmt *parser.DropTableStmt) (*Result, error) {
  3862. // Dropping a table can remove the parent or child side of a FOREIGN KEY.
  3863. // Serialize the DDL with point writes so a concurrent insert or delete cannot
  3864. // validate against a constraint that is being removed.
  3865. if e.table != nil {
  3866. unlockFK := e.table.LockForeignKeyWriteGate()
  3867. defer unlockFK()
  3868. }
  3869. for _, tableRef := range stmt.Tables {
  3870. if !e.session.TableExists(tableRef.Name) {
  3871. if stmt.IfExists {
  3872. continue
  3873. }
  3874. return nil, fmt.Errorf("table not found: %s", tableRef.Name)
  3875. }
  3876. if err := e.rejectForeignKeyDependentTableDrop(tableRef.Name); err != nil {
  3877. return nil, err
  3878. }
  3879. // First, drop all indexes associated with this table
  3880. indexes, _ := e.session.ListTableIndexes(tableRef.Name)
  3881. for _, idx := range indexes {
  3882. // Clear index entries
  3883. columns := make([]string, len(idx.Columns))
  3884. for i, col := range idx.Columns {
  3885. columns[i] = col.Name
  3886. }
  3887. e.session.ClearIndex(idx.Name, tableRef.Name, columns)
  3888. // Drop the index schema
  3889. e.session.DropIndex(idx.Name)
  3890. }
  3891. // DropTable removes durable rows and schema state together.
  3892. if err := e.session.DropTable(tableRef.Name); err != nil {
  3893. return nil, err
  3894. }
  3895. e.session.InvalidateCache(tableRef.Name)
  3896. }
  3897. if err := e.SyncCatalog(); err != nil {
  3898. return nil, err
  3899. }
  3900. result := NewResult("DROP TABLE")
  3901. return result, nil
  3902. }
  3903. // executeCreateIndex creates a new index.
  3904. func (e *Executor) executeCreateIndex(stmt *parser.CreateIndexStmt) (*Result, error) {
  3905. // Check if index already exists
  3906. if e.session.IndexExists(stmt.Name) {
  3907. if stmt.IfNotExists {
  3908. result := NewResult("CREATE INDEX")
  3909. return result, nil
  3910. }
  3911. return nil, fmt.Errorf("index already exists: %s", stmt.Name)
  3912. }
  3913. // Verify table exists
  3914. if !e.session.TableExists(stmt.Table) {
  3915. return nil, fmt.Errorf("table not found: %s", stmt.Table)
  3916. }
  3917. // Verify columns exist
  3918. schema, err := e.session.GetSchema(stmt.Table)
  3919. if err != nil {
  3920. return nil, err
  3921. }
  3922. for _, col := range stmt.Columns {
  3923. if col.Expr != nil {
  3924. // Expression indexes are evaluated by the stateless evaluator; make
  3925. // sure the persisted text parses, is deterministic, and only
  3926. // references columns of the indexed table.
  3927. text := parser.FormatExpr(col.Expr)
  3928. if _, err := parseStoredExpr(text); err != nil {
  3929. return nil, err
  3930. }
  3931. if err := ValidateIndexColumns(col.Expr, schema); err != nil {
  3932. return nil, err
  3933. }
  3934. continue
  3935. }
  3936. if _, found := schema.GetColumn(col.Name); !found {
  3937. return nil, fmt.Errorf("column not found: %s", col.Name)
  3938. }
  3939. }
  3940. // Create storage index
  3941. index := &storage.Index{
  3942. Name: stmt.Name,
  3943. Table: stmt.Table,
  3944. Unique: stmt.Unique,
  3945. }
  3946. for _, col := range stmt.Columns {
  3947. ic := storage.IndexColumn{
  3948. Name: col.Name,
  3949. Desc: col.Desc,
  3950. }
  3951. if col.Expr != nil {
  3952. ic.Expression = parser.FormatExpr(col.Expr)
  3953. }
  3954. index.Columns = append(index.Columns, ic)
  3955. }
  3956. // A UNIQUE index is validated against the rows this session observes (the
  3957. // autocommit path does so under the table's exclusive gate), and inside a
  3958. // transaction the definition is staged for the commit instead.
  3959. if err := e.session.CreateIndex(index); err != nil {
  3960. if stmt.IfNotExists && strings.Contains(err.Error(), "index already exists") {
  3961. return NewResult("CREATE INDEX"), nil
  3962. }
  3963. return nil, err
  3964. }
  3965. // Build index entries for existing rows
  3966. columns := make([]string, len(stmt.Columns))
  3967. for i, col := range stmt.Columns {
  3968. columns[i] = col.Name
  3969. }
  3970. if err := e.session.BuildIndex(stmt.Name, stmt.Table, columns); err != nil {
  3971. // Rollback index creation on failure
  3972. e.session.DropIndex(stmt.Name)
  3973. return nil, fmt.Errorf("failed to build index: %w", err)
  3974. }
  3975. result := NewResult("CREATE INDEX")
  3976. return result, nil
  3977. }
  3978. // executeDropIndex drops an index.
  3979. func (e *Executor) executeDropIndex(stmt *parser.DropIndexStmt) (*Result, error) {
  3980. if !e.session.IndexExists(stmt.Name) {
  3981. if stmt.IfExists {
  3982. result := NewResult("DROP INDEX")
  3983. return result, nil
  3984. }
  3985. return nil, fmt.Errorf("index not found: %s", stmt.Name)
  3986. }
  3987. // Get index info to clear entries
  3988. index, err := e.session.GetIndex(stmt.Name)
  3989. if err == nil && index != nil {
  3990. columns := make([]string, len(index.Columns))
  3991. for i, col := range index.Columns {
  3992. columns[i] = col.Name
  3993. }
  3994. e.session.ClearIndex(stmt.Name, index.Table, columns)
  3995. }
  3996. if err := e.session.DropIndex(stmt.Name); err != nil {
  3997. return nil, err
  3998. }
  3999. result := NewResult("DROP INDEX")
  4000. return result, nil
  4001. }
  4002. func (e *Executor) executeCreateView(stmt *parser.CreateViewStmt) (*Result, error) {
  4003. name := strings.ToLower(stmt.View.Name)
  4004. if _, exists := e.views[name]; exists {
  4005. if stmt.IfNotExists {
  4006. return NewResult("CREATE VIEW"), nil
  4007. }
  4008. return nil, fmt.Errorf("view already exists: %s", stmt.View.Name)
  4009. }
  4010. e.views[name] = stmt.Select
  4011. // Derive view columns from SELECT list for catalog registration.
  4012. var viewCols []analyzer.ColumnInfo
  4013. hasStar := false
  4014. for _, col := range stmt.Select.Columns {
  4015. if col.Star {
  4016. hasStar = true
  4017. break
  4018. }
  4019. colName := col.Alias
  4020. if colName == "" {
  4021. if ref, ok := col.Expr.(*parser.ColumnRef); ok {
  4022. colName = ref.Column
  4023. } else {
  4024. colName = fmt.Sprintf("col_%d", len(viewCols))
  4025. }
  4026. }
  4027. viewCols = append(viewCols, analyzer.ColumnInfo{
  4028. Name: colName,
  4029. TableName: stmt.View.Name,
  4030. Type: analyzer.TypeAny,
  4031. Nullable: true,
  4032. })
  4033. }
  4034. // For SELECT *, pull columns from the underlying table(s).
  4035. if hasStar && len(stmt.Select.From) > 0 {
  4036. baseName := stmt.Select.From[0].Name
  4037. if schema, err := e.session.GetSchema(baseName); err == nil {
  4038. for _, c := range schema.Columns {
  4039. viewCols = append(viewCols, analyzer.ColumnInfo{
  4040. Name: c.Name,
  4041. TableName: stmt.View.Name,
  4042. Type: analyzer.TypeAny,
  4043. Nullable: true,
  4044. })
  4045. }
  4046. }
  4047. }
  4048. // Register in catalog so the analyzer accepts SELECT FROM this view.
  4049. e.catalog.CreateTable(&analyzer.TableInfo{ //nolint:errcheck
  4050. Name: stmt.View.Name,
  4051. Columns: viewCols,
  4052. IsView: true,
  4053. })
  4054. return NewResult("CREATE VIEW"), nil
  4055. }
  4056. func (e *Executor) executeDropView(stmt *parser.DropViewStmt) (*Result, error) {
  4057. for _, ref := range stmt.Views {
  4058. name := strings.ToLower(ref.Name)
  4059. if _, exists := e.views[name]; !exists {
  4060. if stmt.IfExists {
  4061. continue
  4062. }
  4063. return nil, fmt.Errorf("view not found: %s", ref.Name)
  4064. }
  4065. delete(e.views, name)
  4066. e.catalog.DropTable(ref.Name) //nolint:errcheck
  4067. }
  4068. return NewResult("DROP VIEW"), nil
  4069. }
  4070. // executeAlterTable executes an ALTER TABLE statement.
  4071. func (e *Executor) executeAlterTable(stmt *parser.AlterTableStmt) (*Result, error) {
  4072. switch action := stmt.Action.(type) {
  4073. case *parser.AddColumnAction:
  4074. return e.executeAlterTableAddColumn(stmt.Table, action)
  4075. case *parser.DropColumnAction:
  4076. return e.executeAlterTableDropColumn(stmt.Table, action)
  4077. case *parser.RenameTableAction:
  4078. return e.executeAlterTableRename(stmt.Table, action)
  4079. case *parser.RenameColumnAction:
  4080. return e.executeAlterTableRenameColumn(stmt.Table, action)
  4081. default:
  4082. return nil, fmt.Errorf("unsupported ALTER TABLE action: %T", action)
  4083. }
  4084. }
  4085. // executeAlterTableAddColumn adds a column to a table. A DEFAULT is written
  4086. // into every existing row (see SchemaManager.AddColumn), so the column reads
  4087. // the default on rows that predate the statement as well as on later INSERTs
  4088. // that omit it. A constant default is copied from the catalog; a non-constant
  4089. // one is evaluated at a single instant sampled for the ALTER statement, so
  4090. // validation and the backfill write the same CURRENT_TIMESTAMP value.
  4091. func (e *Executor) executeAlterTableAddColumn(table string, action *parser.AddColumnAction) (*Result, error) {
  4092. schema, err := e.session.GetSchema(table)
  4093. if err != nil {
  4094. return nil, err
  4095. }
  4096. if _, exists := schema.GetColumn(action.Column.Name); exists {
  4097. if action.IfNotExists {
  4098. return NewResult("ALTER TABLE"), nil
  4099. }
  4100. return nil, fmt.Errorf("column already exists: %s", action.Column.Name)
  4101. }
  4102. col := storage.Column{
  4103. Name: action.Column.Name,
  4104. Type: action.Column.Type.SQLTypeName(),
  4105. Nullable: true,
  4106. }
  4107. var uniqueConstraint *parser.ColumnConstraint
  4108. var checkConstraints []parser.ColumnConstraint
  4109. // Process column constraints
  4110. for _, constraint := range action.Column.Constraints {
  4111. switch constraint.Type {
  4112. case parser.ConstraintPrimaryKey:
  4113. return nil, pgerror.Unsupported(
  4114. "ALTER TABLE ADD COLUMN cannot declare PRIMARY KEY on column %q; declare the key in CREATE TABLE (SQLite also rejects adding a PRIMARY KEY column)",
  4115. col.Name,
  4116. )
  4117. case parser.ConstraintNotNull:
  4118. col.Nullable = false
  4119. case parser.ConstraintUnique:
  4120. unique := constraint
  4121. uniqueConstraint = &unique
  4122. case parser.ConstraintDefault:
  4123. if constraint.Default != nil {
  4124. val, exprText, err := defaultColumnValue(e, col.Name, constraint.Default)
  4125. if err != nil {
  4126. return nil, err
  4127. }
  4128. val, exprText, err = canonicalArrayDefault(col.Type, val, exprText)
  4129. if err != nil {
  4130. return nil, err
  4131. }
  4132. col.Default = val
  4133. col.DefaultExpr = exprText
  4134. }
  4135. case parser.ConstraintCheck:
  4136. // Validated with the other CHECK predicates once the column shape is
  4137. // final, so the predicate can reference the column being added.
  4138. checkConstraints = append(checkConstraints, constraint)
  4139. case parser.ConstraintForeignKey:
  4140. return nil, pgerror.Unsupported(
  4141. "ALTER TABLE ADD COLUMN cannot declare REFERENCES %s on column %q; declare the foreign key in CREATE TABLE",
  4142. constraint.RefTable, col.Name,
  4143. )
  4144. }
  4145. }
  4146. var uniqueIndex *storage.Index
  4147. if uniqueConstraint != nil {
  4148. uniqueIndex = e.addColumnUniqueIndex(table, col.Name, uniqueConstraint)
  4149. }
  4150. // The schema manager validates the new column against durable rows, rewrites
  4151. // them, and publishes the column together with its CHECK constraints and
  4152. // UNIQUE index while holding the table's exclusive gate, so a writer cannot
  4153. // slip a row in between the validation and the publication. Rows this session
  4154. // staged in an open transaction are invisible to that scan, so reject them
  4155. // here as well; the commit re-validates them against the schema that is
  4156. // current by then.
  4157. if !col.Nullable && col.Default == nil && col.DefaultExpr == "" {
  4158. stagedRows, err := e.session.CountFast(table)
  4159. if err != nil {
  4160. return nil, err
  4161. }
  4162. if stagedRows > 0 {
  4163. return nil, &storage.NotNullViolationError{Table: table, Column: col.Name}
  4164. }
  4165. }
  4166. checks, err := e.tableChecks(schemaWithColumn(schema, col), checkConstraints, nil)
  4167. if err != nil {
  4168. return nil, err
  4169. }
  4170. if err := e.session.AddColumn(table, col, checks, uniqueIndex); err != nil {
  4171. if action.IfNotExists && strings.Contains(err.Error(), "column already exists") {
  4172. return NewResult("ALTER TABLE"), nil
  4173. }
  4174. return nil, err
  4175. }
  4176. // Update catalog
  4177. e.SyncCatalog()
  4178. result := NewResult("ALTER TABLE")
  4179. return result, nil
  4180. }
  4181. // addColumnUniqueIndex names the index an ADD COLUMN ... UNIQUE constraint
  4182. // materializes, using the declared constraint name when there is one and the
  4183. // same deterministic internal name CREATE TABLE gives an unnamed column-level
  4184. // UNIQUE constraint otherwise, suffixing collisions.
  4185. func (e *Executor) addColumnUniqueIndex(table, column string, constraint *parser.ColumnConstraint) *storage.Index {
  4186. base := "uniq_" + strings.ToLower(table) + "_" + strings.ToLower(column)
  4187. if constraint.Name != "" {
  4188. base = constraint.Name
  4189. }
  4190. name := base
  4191. for n := 2; e.session.IndexExists(name); n++ {
  4192. name = fmt.Sprintf("%s_%d", base, n)
  4193. }
  4194. index := &storage.Index{
  4195. Name: name,
  4196. Table: table,
  4197. Unique: true,
  4198. Columns: []storage.IndexColumn{{Name: column}},
  4199. }
  4200. if constraint.HasOnConflict {
  4201. index.OnConflict = conflictActionName(constraint.OnConflict)
  4202. }
  4203. return index
  4204. }
  4205. // executeAlterTableDropColumn drops a column from a table.
  4206. func (e *Executor) executeAlterTableDropColumn(table string, action *parser.DropColumnAction) (*Result, error) {
  4207. if err := e.rejectCheckColumnChange(table, action.Column, "drop"); err != nil {
  4208. return nil, err
  4209. }
  4210. if err := e.rejectForeignKeyColumnChange(table, action.Column, "drop"); err != nil {
  4211. return nil, err
  4212. }
  4213. if err := e.session.DropColumn(table, action.Column); err != nil {
  4214. return nil, err
  4215. }
  4216. // Update catalog
  4217. e.SyncCatalog()
  4218. result := NewResult("ALTER TABLE")
  4219. return result, nil
  4220. }
  4221. // executeAlterTableRename renames a table.
  4222. func (e *Executor) executeAlterTableRename(table string, action *parser.RenameTableAction) (*Result, error) {
  4223. if err := e.rejectForeignKeyTableRename(table); err != nil {
  4224. return nil, err
  4225. }
  4226. if err := e.session.RenameTable(table, action.NewName); err != nil {
  4227. return nil, err
  4228. }
  4229. e.session.InvalidateCache(table)
  4230. e.session.InvalidateCache(action.NewName)
  4231. // Update catalog
  4232. e.SyncCatalog()
  4233. result := NewResult("ALTER TABLE")
  4234. return result, nil
  4235. }
  4236. // executeAlterTableRenameColumn renames a column.
  4237. func (e *Executor) executeAlterTableRenameColumn(table string, action *parser.RenameColumnAction) (*Result, error) {
  4238. if err := e.rejectExpressionIndexRename(table, action.OldName); err != nil {
  4239. return nil, err
  4240. }
  4241. if err := e.rejectCheckColumnChange(table, action.OldName, "rename"); err != nil {
  4242. return nil, err
  4243. }
  4244. if err := e.rejectForeignKeyColumnChange(table, action.OldName, "rename"); err != nil {
  4245. return nil, err
  4246. }
  4247. if err := e.session.RenameColumn(table, action.OldName, action.NewName); err != nil {
  4248. return nil, err
  4249. }
  4250. // Update catalog
  4251. e.SyncCatalog()
  4252. result := NewResult("ALTER TABLE")
  4253. return result, nil
  4254. }
  4255. // rejectExpressionIndexRename refuses to rename a column that a stored index
  4256. // expression references. Expression text is persisted verbatim, so the rename
  4257. // cannot rewrite it; leaving the old identifier behind would silently unbind a
  4258. // UNIQUE expression index, because its rows no longer resolve the referenced
  4259. // column.
  4260. func (e *Executor) rejectExpressionIndexRename(table, column string) error {
  4261. indexes, err := e.session.ListTableIndexes(table)
  4262. if err != nil {
  4263. return err
  4264. }
  4265. for _, idx := range indexes {
  4266. for _, ic := range idx.Columns {
  4267. if ic.Expression == "" {
  4268. continue
  4269. }
  4270. references, err := storedExpressionReferencesColumn(ic.Expression, column)
  4271. if err != nil {
  4272. return fmt.Errorf("index %s: %w", idx.Name, err)
  4273. }
  4274. if references {
  4275. return pgerror.Unsupported(
  4276. "cannot rename column %s: index %s depends on it through the expression %s; drop the index, rename the column, then recreate the index",
  4277. column, idx.Name, ic.Expression,
  4278. )
  4279. }
  4280. }
  4281. }
  4282. return nil
  4283. }
  4284. // Transaction execution methods
  4285. // executeBegin starts a new transaction.
  4286. func (e *Executor) executeBegin(stmt *parser.BeginStmt) (*Result, error) {
  4287. if e.inTransaction {
  4288. return nil, fmt.Errorf("cannot start a transaction within a transaction")
  4289. }
  4290. if err := e.session.Begin(); err != nil {
  4291. return nil, err
  4292. }
  4293. e.inTransaction = true
  4294. e.savepoints = nil
  4295. e.savepointStates = nil
  4296. e.clearNotificationState()
  4297. result := NewResult("BEGIN")
  4298. return result, nil
  4299. }
  4300. // executeCommit commits the current transaction.
  4301. func (e *Executor) executeCommit(stmt *parser.CommitStmt) (*Result, error) {
  4302. if !e.inTransaction {
  4303. return nil, fmt.Errorf("cannot commit: %w", ErrNoTransaction)
  4304. }
  4305. lsn, err := e.session.CommitWithLSN()
  4306. if err != nil {
  4307. e.inTransaction = false
  4308. e.savepoints = nil
  4309. e.savepointStates = nil
  4310. e.finishRollback()
  4311. return nil, err
  4312. }
  4313. e.inTransaction = false
  4314. e.savepoints = nil
  4315. e.savepointStates = nil
  4316. e.finishCommit(lsn)
  4317. result := NewResult("COMMIT")
  4318. result.LSN = lsn
  4319. return result, nil
  4320. }
  4321. // executeRollback rolls back the current transaction or to a savepoint.
  4322. func (e *Executor) executeRollback(stmt *parser.RollbackStmt) (*Result, error) {
  4323. if !e.inTransaction {
  4324. return nil, fmt.Errorf("cannot rollback: %w", ErrNoTransaction)
  4325. }
  4326. if stmt.Savepoint != "" {
  4327. // Rollback to savepoint
  4328. return e.rollbackToSavepoint(stmt.Savepoint)
  4329. }
  4330. if err := e.session.Rollback(); err != nil {
  4331. return nil, err
  4332. }
  4333. e.inTransaction = false
  4334. e.savepoints = nil
  4335. e.savepointStates = nil
  4336. e.finishRollback()
  4337. // total_changes() is monotonic (SQLite semantics): it is NOT decremented on
  4338. // rollback. last_insert_rowid() and changes() also intentionally hold.
  4339. result := NewResult("ROLLBACK")
  4340. return result, nil
  4341. }
  4342. // executeSavepoint creates a savepoint.
  4343. func (e *Executor) executeSavepoint(stmt *parser.SavepointStmt) (*Result, error) {
  4344. if !e.inTransaction {
  4345. // SQLite allows SAVEPOINT outside transaction (starts implicit transaction)
  4346. if err := e.session.Begin(); err != nil {
  4347. return nil, err
  4348. }
  4349. e.inTransaction = true
  4350. e.savepoints = nil
  4351. e.savepointStates = nil
  4352. e.clearNotificationState()
  4353. }
  4354. // Add savepoint marker
  4355. e.savepoints = append(e.savepoints, stmt.Name)
  4356. e.savepointStates = append(e.savepointStates, e.session.Savepoint())
  4357. e.notificationSaves = append(e.notificationSaves, e.notificationSnapshot())
  4358. result := NewResult("SAVEPOINT")
  4359. return result, nil
  4360. }
  4361. // executeRelease releases a savepoint.
  4362. func (e *Executor) executeRelease(stmt *parser.ReleaseStmt) (*Result, error) {
  4363. if !e.inTransaction {
  4364. return nil, fmt.Errorf("cannot release savepoint: %w", ErrNoTransaction)
  4365. }
  4366. // Find and remove the savepoint
  4367. found := false
  4368. for i := len(e.savepoints) - 1; i >= 0; i-- {
  4369. if e.savepoints[i] == stmt.Name {
  4370. e.savepoints = e.savepoints[:i]
  4371. e.savepointStates = e.savepointStates[:i]
  4372. if i <= len(e.notificationSaves) {
  4373. e.notificationSaves = e.notificationSaves[:i]
  4374. }
  4375. found = true
  4376. break
  4377. }
  4378. }
  4379. if !found {
  4380. return nil, fmt.Errorf("no such savepoint: %s", stmt.Name)
  4381. }
  4382. result := NewResult("RELEASE")
  4383. return result, nil
  4384. }
  4385. // executeAttach attaches a database.
  4386. func (e *Executor) executeAttach(stmt *parser.AttachStmt) (*Result, error) {
  4387. // Check if alias already exists
  4388. if _, exists := e.attachedDatabases[stmt.Alias]; exists {
  4389. return nil, fmt.Errorf("database alias already exists: %s", stmt.Alias)
  4390. }
  4391. // Reserved alias check
  4392. if strings.EqualFold(stmt.Alias, "temp") || strings.EqualFold(stmt.Alias, "temporary") {
  4393. return nil, fmt.Errorf("reserved database alias: %s", stmt.Alias)
  4394. }
  4395. // Get the pool from the main schema manager
  4396. pool := e.schema.GetPool()
  4397. // Create new schema and table managers for the attached database
  4398. // In PizzaKV, each database is just a different namespace/prefix
  4399. schema := storage.NewSchemaManager(pool, stmt.FilePath)
  4400. table := storage.NewTableManager(pool, schema, stmt.FilePath)
  4401. // Register the database connection
  4402. e.attachedDatabases[stmt.Alias] = &DatabaseConnection{
  4403. Alias: stmt.Alias,
  4404. Path: stmt.FilePath,
  4405. Schema: schema,
  4406. Table: table,
  4407. }
  4408. // Sync the catalog with the attached database's tables
  4409. tables, _ := schema.ListTables()
  4410. for _, tableName := range tables {
  4411. tSchema, err := schema.GetSchema(tableName)
  4412. if err != nil {
  4413. continue
  4414. }
  4415. // Add with database prefix
  4416. tableInfo := tSchema.ToAnalyzerTableInfo()
  4417. tableInfo.Name = stmt.Alias + "." + tableInfo.Name
  4418. e.catalog.CreateTable(tableInfo)
  4419. }
  4420. result := NewResult("ATTACH")
  4421. return result, nil
  4422. }
  4423. // executeDetach detaches a database.
  4424. func (e *Executor) executeDetach(stmt *parser.DetachStmt) (*Result, error) {
  4425. // Cannot detach main database
  4426. if strings.EqualFold(stmt.Alias, "main") {
  4427. return nil, fmt.Errorf("cannot detach main database")
  4428. }
  4429. // Check if database exists
  4430. if _, exists := e.attachedDatabases[stmt.Alias]; !exists {
  4431. return nil, fmt.Errorf("no such database: %s", stmt.Alias)
  4432. }
  4433. // Remove from attached databases
  4434. delete(e.attachedDatabases, stmt.Alias)
  4435. // Note: We don't remove from catalog as that would be more complex
  4436. // In a production system, we'd need to track which tables belong to which database
  4437. result := NewResult("DETACH")
  4438. return result, nil
  4439. }
  4440. // rollbackToSavepoint rolls back to a specific savepoint.
  4441. func (e *Executor) rollbackToSavepoint(name string) (*Result, error) {
  4442. // Find savepoint index
  4443. savepointIdx := -1
  4444. for i := len(e.savepoints) - 1; i >= 0; i-- {
  4445. if e.savepoints[i] == name {
  4446. savepointIdx = i
  4447. break
  4448. }
  4449. }
  4450. if savepointIdx == -1 {
  4451. return nil, fmt.Errorf("no such savepoint: %s", name)
  4452. }
  4453. e.session.RollbackToSavepoint(e.savepointStates[savepointIdx])
  4454. if savepointIdx < len(e.notificationSaves) {
  4455. e.rollbackNotificationsTo(e.notificationSaves[savepointIdx])
  4456. e.notificationSaves = e.notificationSaves[:savepointIdx+1]
  4457. }
  4458. // Remove savepoints after the target
  4459. e.savepoints = e.savepoints[:savepointIdx+1]
  4460. e.savepointStates = e.savepointStates[:savepointIdx+1]
  4461. result := NewResult("ROLLBACK")
  4462. return result, nil
  4463. }
  4464. // RollbackActive rolls back an open transaction, such as when its client
  4465. // disconnects before sending COMMIT or ROLLBACK.
  4466. func (e *Executor) RollbackActive() error {
  4467. if !e.inTransaction {
  4468. return nil
  4469. }
  4470. _, err := e.executeRollback(&parser.RollbackStmt{})
  4471. return err
  4472. }
  4473. // extractIndexableCondition extracts column name and value from a simple equality condition.
  4474. // Returns (column, value, true) if the expression is column = literal.
  4475. func (e *Executor) extractIndexableCondition(expr parser.Expr) (string, interface{}, bool) {
  4476. binExpr, ok := expr.(*parser.BinaryExpr)
  4477. if !ok {
  4478. return "", nil, false
  4479. }
  4480. // Only handle equality for now
  4481. if binExpr.Op != lexer.TokenEq {
  4482. return "", nil, false
  4483. }
  4484. // Check for column = literal pattern
  4485. colRef, leftIsCol := binExpr.Left.(*parser.ColumnRef)
  4486. litExpr, rightIsLit := binExpr.Right.(*parser.LiteralExpr)
  4487. if leftIsCol && rightIsLit && colRef.Table == "" {
  4488. val, _ := e.evalLiteral(litExpr)
  4489. return colRef.Column, val, true
  4490. }
  4491. // Check for literal = column pattern
  4492. litExpr, leftIsLit := binExpr.Left.(*parser.LiteralExpr)
  4493. colRef, rightIsCol := binExpr.Right.(*parser.ColumnRef)
  4494. if leftIsLit && rightIsCol && colRef.Table == "" {
  4495. val, _ := e.evalLiteral(litExpr)
  4496. return colRef.Column, val, true
  4497. }
  4498. return "", nil, false
  4499. }
  4500. // Bound only simple scans. Final OFFSET/LIMIT is still applied once by the
  4501. // normal result path; transactions conservatively retain their full read set.
  4502. func scanLimit(stmt *parser.SelectStmt) (int, bool) {
  4503. if stmt.Limit == nil || len(stmt.From) != 1 || stmt.From[0].Join != nil ||
  4504. stmt.From[0].Alias != "" || stmt.Distinct || len(stmt.GroupBy) != 0 ||
  4505. stmt.Having != nil || len(stmt.OrderBy) != 0 || stmt.Compound != nil || len(stmt.With) != 0 {
  4506. return 0, false
  4507. }
  4508. for _, column := range stmt.Columns {
  4509. switch column.Expr.(type) {
  4510. case *parser.ColumnRef, *parser.LiteralExpr:
  4511. default:
  4512. if !column.Star {
  4513. return 0, false
  4514. }
  4515. }
  4516. }
  4517. literalInt := func(expr parser.Expr) (int, bool) {
  4518. literal, ok := expr.(*parser.LiteralExpr)
  4519. if !ok || literal.Type != lexer.TokenNumber {
  4520. return 0, false
  4521. }
  4522. n, err := strconv.Atoi(literal.Value)
  4523. return n, err == nil && n >= 0
  4524. }
  4525. limit, ok := literalInt(stmt.Limit)
  4526. if !ok {
  4527. return 0, false
  4528. }
  4529. if limit == 0 {
  4530. return 0, true
  4531. }
  4532. if stmt.Offset != nil {
  4533. offset, valid := literalInt(stmt.Offset)
  4534. if !valid || offset > int(^uint(0)>>1)-limit {
  4535. return 0, false
  4536. }
  4537. limit += offset
  4538. }
  4539. return limit, true
  4540. }
  4541. func (e *Executor) extractSelectLookupCondition(expr parser.Expr, table parser.TableRef) (string, interface{}, bool) {
  4542. for join := table.Join; join != nil; join = join.Table.Join {
  4543. if join.Type == parser.JoinRight || join.Type == parser.JoinFull {
  4544. return "", nil, false
  4545. }
  4546. }
  4547. bin, ok := expr.(*parser.BinaryExpr)
  4548. if !ok {
  4549. return "", nil, false
  4550. }
  4551. copyExpr := *bin
  4552. for _, side := range []*parser.Expr{&copyExpr.Left, &copyExpr.Right} {
  4553. if column, ok := (*side).(*parser.ColumnRef); ok {
  4554. if column.Table == "" && table.Join != nil {
  4555. return "", nil, false
  4556. }
  4557. qualifier := table.Alias
  4558. if qualifier == "" {
  4559. qualifier = table.Name
  4560. }
  4561. if column.Table != "" && !strings.EqualFold(column.Table, qualifier) {
  4562. return "", nil, false
  4563. }
  4564. copyColumn := *column
  4565. copyColumn.Table = ""
  4566. *side = &copyColumn
  4567. }
  4568. }
  4569. return e.extractIndexableCondition(&copyExpr)
  4570. }
  4571. // Numeric strings can compare equal to differently formatted primary keys;
  4572. // a direct durable-key lookup would miss them. Keep those comparisons on the
  4573. // scan path until primary-key affinity has a canonical storage representation.
  4574. func safePrimaryKeyLiteral(value interface{}) bool {
  4575. if value == nil {
  4576. return false
  4577. }
  4578. if text, ok := value.(string); ok {
  4579. _, numeric := toNumeric(text)
  4580. return !numeric
  4581. }
  4582. return true
  4583. }
  4584. // executePragma executes a PRAGMA statement.
  4585. func (e *Executor) executePragma(stmt *parser.PragmaStmt) (*Result, error) {
  4586. switch stmt.Name {
  4587. case "table_info":
  4588. return e.pragmaTableInfo(stmt.Arg)
  4589. case "table_list":
  4590. return e.pragmaTableList()
  4591. case "database_list":
  4592. return e.pragmaDatabaseList()
  4593. case "version":
  4594. return e.pragmaVersion()
  4595. case "foreign_keys":
  4596. // Foreign keys are always enforced, so the pragma reports them as on.
  4597. // Enabling is a no-op; disabling would require silently dropping
  4598. // constraint enforcement, which the engine does not offer.
  4599. result := NewResult("PRAGMA")
  4600. if stmt.Value == nil {
  4601. result.AddColumn("foreign_keys")
  4602. result.AddRow(int64(1))
  4603. return result, nil
  4604. }
  4605. if ref, ok := stmt.Value.(*parser.ColumnRef); ok && (strings.EqualFold(ref.Column, "on") || strings.EqualFold(ref.Column, "off")) {
  4606. if strings.EqualFold(ref.Column, "off") {
  4607. return nil, pgerror.Unsupported("foreign keys are always enforced; PRAGMA foreign_keys = OFF is not supported (SQLite defaults it to OFF)")
  4608. }
  4609. return result, nil
  4610. }
  4611. if literal, ok := stmt.Value.(*parser.LiteralExpr); ok && (literal.Value == "1" || literal.Value == "0") {
  4612. if literal.Value == "0" {
  4613. return nil, pgerror.Unsupported("foreign keys are always enforced; PRAGMA foreign_keys = OFF is not supported (SQLite defaults it to OFF)")
  4614. }
  4615. return result, nil
  4616. }
  4617. return nil, pgerror.Unsupported("PRAGMA foreign_keys accepts ON or OFF")
  4618. default:
  4619. return nil, fmt.Errorf("unknown pragma: %s", stmt.Name)
  4620. }
  4621. }
  4622. // pragmaTableInfo returns column information for a table.
  4623. func (e *Executor) pragmaTableInfo(tableName string) (*Result, error) {
  4624. if tableName == "" {
  4625. return nil, fmt.Errorf("table_info requires a table name")
  4626. }
  4627. schema, err := e.session.GetSchema(tableName)
  4628. if err != nil {
  4629. return nil, err
  4630. }
  4631. result := NewResult("PRAGMA")
  4632. result.AddColumn("cid")
  4633. result.AddColumn("name")
  4634. result.AddColumn("type")
  4635. result.AddColumn("notnull")
  4636. result.AddColumn("dflt_value")
  4637. result.AddColumn("pk")
  4638. for i, col := range schema.Columns {
  4639. notnull := 0
  4640. if !col.Nullable {
  4641. notnull = 1
  4642. }
  4643. result.AddRow(int64(i), col.Name, col.Type, int64(notnull), col.DefaultLiteral(), int64(primaryKeyOrdinal(schema, col.Name)))
  4644. }
  4645. return result, nil
  4646. }
  4647. // pragmaTableList returns a list of all tables.
  4648. func (e *Executor) pragmaTableList() (*Result, error) {
  4649. tables, err := e.session.ListTables()
  4650. if err != nil {
  4651. return nil, err
  4652. }
  4653. result := NewResult("PRAGMA")
  4654. result.AddColumn("schema")
  4655. result.AddColumn("name")
  4656. result.AddColumn("type")
  4657. for _, t := range tables {
  4658. result.AddRow("main", t, "table")
  4659. }
  4660. return result, nil
  4661. }
  4662. // pragmaDatabaseList returns a list of databases.
  4663. func (e *Executor) pragmaDatabaseList() (*Result, error) {
  4664. result := NewResult("PRAGMA")
  4665. result.AddColumn("seq")
  4666. result.AddColumn("name")
  4667. result.AddColumn("file")
  4668. // We only have one database
  4669. result.AddRow(int64(0), "main", "")
  4670. return result, nil
  4671. }
  4672. // pragmaVersion returns the PizzaSQL version.
  4673. func (e *Executor) pragmaVersion() (*Result, error) {
  4674. result := NewResult("PRAGMA")
  4675. result.AddColumn("version")
  4676. result.AddRow(version.String())
  4677. return result, nil
  4678. }
  4679. // executeExplain executes an EXPLAIN statement.
  4680. // executeAnalyze accepts ANALYZE as a documented no-op. PizzaSQL has no
  4681. // cost-based optimizer or persisted statistics, so there is nothing to gather;
  4682. // the statement exists so SQLite migrations that end with ANALYZE succeed.
  4683. func (e *Executor) executeAnalyze(stmt *parser.AnalyzeStmt) (*Result, error) {
  4684. return NewResult("ANALYZE"), nil
  4685. }
  4686. func (e *Executor) executeExplain(stmt *parser.ExplainStmt) (*Result, error) {
  4687. result := NewResult("EXPLAIN")
  4688. if stmt.QueryPlan {
  4689. // EXPLAIN QUERY PLAN format
  4690. result.AddColumn("id")
  4691. result.AddColumn("parent")
  4692. result.AddColumn("notused")
  4693. result.AddColumn("detail")
  4694. plan := e.generateQueryPlan(stmt.Statement)
  4695. for i, step := range plan {
  4696. result.AddRow(int64(i), int64(0), int64(0), step)
  4697. }
  4698. } else {
  4699. // Simple EXPLAIN format
  4700. result.AddColumn("addr")
  4701. result.AddColumn("opcode")
  4702. result.AddColumn("p1")
  4703. result.AddColumn("p2")
  4704. result.AddColumn("p3")
  4705. result.AddColumn("p4")
  4706. result.AddColumn("p5")
  4707. result.AddColumn("comment")
  4708. ops := e.generateOpcodes(stmt.Statement)
  4709. for i, op := range ops {
  4710. result.AddRow(int64(i), op, int64(0), int64(0), int64(0), "", int64(0), "")
  4711. }
  4712. }
  4713. return result, nil
  4714. }
  4715. // generateQueryPlan generates a simple query plan description.
  4716. func (e *Executor) generateQueryPlan(stmt parser.Statement) []string {
  4717. var plan []string
  4718. switch s := stmt.(type) {
  4719. case *parser.SelectStmt:
  4720. if len(s.From) > 0 {
  4721. plan = append(plan, fmt.Sprintf("SCAN TABLE %s", s.From[0].Name))
  4722. if s.Where != nil {
  4723. plan = append(plan, "FILTER")
  4724. }
  4725. if len(s.OrderBy) > 0 {
  4726. plan = append(plan, "SORT")
  4727. }
  4728. if s.Limit != nil {
  4729. plan = append(plan, "LIMIT")
  4730. }
  4731. } else {
  4732. plan = append(plan, "SCALAR EXPRESSION")
  4733. }
  4734. case *parser.InsertStmt:
  4735. plan = append(plan, fmt.Sprintf("INSERT INTO %s", s.Table.Name))
  4736. case *parser.UpdateStmt:
  4737. plan = append(plan, fmt.Sprintf("SCAN TABLE %s", s.Table.Name))
  4738. plan = append(plan, "UPDATE")
  4739. case *parser.DeleteStmt:
  4740. plan = append(plan, fmt.Sprintf("SCAN TABLE %s", s.Table.Name))
  4741. plan = append(plan, "DELETE")
  4742. default:
  4743. plan = append(plan, "EXECUTE")
  4744. }
  4745. return plan
  4746. }
  4747. // generateOpcodes generates simplified opcodes for EXPLAIN.
  4748. func (e *Executor) generateOpcodes(stmt parser.Statement) []string {
  4749. var ops []string
  4750. switch s := stmt.(type) {
  4751. case *parser.SelectStmt:
  4752. ops = append(ops, "Init")
  4753. if len(s.From) > 0 {
  4754. ops = append(ops, "OpenRead")
  4755. ops = append(ops, "Rewind")
  4756. ops = append(ops, "Column")
  4757. ops = append(ops, "ResultRow")
  4758. ops = append(ops, "Next")
  4759. ops = append(ops, "Close")
  4760. } else {
  4761. ops = append(ops, "Integer")
  4762. ops = append(ops, "ResultRow")
  4763. }
  4764. ops = append(ops, "Halt")
  4765. case *parser.InsertStmt:
  4766. ops = append(ops, "Init")
  4767. ops = append(ops, "OpenWrite")
  4768. ops = append(ops, "NewRowid")
  4769. ops = append(ops, "Insert")
  4770. ops = append(ops, "Close")
  4771. ops = append(ops, "Halt")
  4772. case *parser.UpdateStmt:
  4773. ops = append(ops, "Init")
  4774. ops = append(ops, "OpenWrite")
  4775. ops = append(ops, "Rewind")
  4776. ops = append(ops, "Column")
  4777. ops = append(ops, "Update")
  4778. ops = append(ops, "Next")
  4779. ops = append(ops, "Close")
  4780. ops = append(ops, "Halt")
  4781. case *parser.DeleteStmt:
  4782. ops = append(ops, "Init")
  4783. ops = append(ops, "OpenWrite")
  4784. ops = append(ops, "Rewind")
  4785. ops = append(ops, "Delete")
  4786. ops = append(ops, "Next")
  4787. ops = append(ops, "Close")
  4788. ops = append(ops, "Halt")
  4789. default:
  4790. ops = append(ops, "Init")
  4791. ops = append(ops, "Halt")
  4792. }
  4793. return ops
  4794. }
  4795. // evalExpr evaluates an expression.
  4796. func (e *Executor) evalExpr(expr parser.Expr, row storage.Row) (interface{}, error) {
  4797. if expr == nil {
  4798. return nil, nil
  4799. }
  4800. switch ex := expr.(type) {
  4801. case *parser.LiteralExpr:
  4802. return e.evalLiteral(ex)
  4803. case *parser.ColumnRef:
  4804. return e.evalColumnRef(ex, row)
  4805. case *parser.BinaryExpr:
  4806. return e.evalBinaryExpr(ex, row)
  4807. case *parser.UnaryExpr:
  4808. return e.evalUnaryExpr(ex, row)
  4809. case *parser.FunctionCall:
  4810. return e.evalFunctionCall(ex, row)
  4811. case *parser.ParenExpr:
  4812. return e.evalExpr(ex.Expr, row)
  4813. case *parser.CaseExpr:
  4814. return e.evalCaseExpr(ex, row)
  4815. case *parser.InExpr:
  4816. return e.evalInExpr(ex, row)
  4817. case *parser.BetweenExpr:
  4818. return e.evalBetweenExpr(ex, row)
  4819. case *parser.LikeExpr:
  4820. return e.evalLikeExpr(ex, row)
  4821. case *parser.IsNullExpr:
  4822. return e.evalIsNullExpr(ex, row)
  4823. case *parser.IsDistinctExpr:
  4824. return e.evalIsDistinctExpr(ex, row)
  4825. case *parser.CastExpr:
  4826. return e.evalCastExpr(ex, row)
  4827. case *parser.SubqueryExpr:
  4828. return e.evalSubqueryExpr(ex, row)
  4829. case *parser.ExistsExpr:
  4830. return e.evalExistsExpr(ex, row)
  4831. case *parser.ArrayExpr:
  4832. return e.evalArrayExpr(ex, row)
  4833. case *parser.SubscriptExpr:
  4834. return e.evalSubscriptExpr(ex, row)
  4835. case *parser.AnyAllExpr:
  4836. return e.evalAnyAllExpr(ex, row)
  4837. default:
  4838. return nil, fmt.Errorf("unsupported expression type: %T", expr)
  4839. }
  4840. }
  4841. func (e *Executor) evalLiteral(lit *parser.LiteralExpr) (interface{}, error) {
  4842. switch lit.Type {
  4843. case lexer.TokenNumber:
  4844. // Check for scientific notation (e.g., 1e+06) or decimal point
  4845. if strings.Contains(lit.Value, ".") || strings.ContainsAny(lit.Value, "eE") {
  4846. f, err := strconv.ParseFloat(lit.Value, 64)
  4847. if err != nil {
  4848. return nil, err
  4849. }
  4850. // If it's a whole number (no fractional part), return as int64
  4851. if f == float64(int64(f)) {
  4852. return int64(f), nil
  4853. }
  4854. return f, nil
  4855. }
  4856. return strconv.ParseInt(lit.Value, 10, 64)
  4857. case lexer.TokenString:
  4858. return lit.Value, nil
  4859. case lexer.TokenBlob:
  4860. // The lexer stores the decoded bytes in the literal, so a blob literal
  4861. // becomes a true []byte value.
  4862. return []byte(lit.Value), nil
  4863. case lexer.TokenNULL:
  4864. return nil, nil
  4865. case lexer.TokenTRUE:
  4866. return true, nil
  4867. case lexer.TokenFALSE:
  4868. return false, nil
  4869. default:
  4870. return lit.Value, nil
  4871. }
  4872. }
  4873. func (e *Executor) evalColumnRef(ref *parser.ColumnRef, row storage.Row) (interface{}, error) {
  4874. // SQLite date/time keywords (CURRENT_TIMESTAMP, CURRENT_DATE, CURRENT_TIME)
  4875. // are lexed as identifiers; resolve them when no real column shadows them.
  4876. if ref.Table == "" {
  4877. if _, has := lookupRowValue(row, ref.Column); !has {
  4878. if val, ok := sqliteCurrentTimeValue(ref.Column); ok {
  4879. return val, nil
  4880. }
  4881. }
  4882. }
  4883. if row == nil {
  4884. return nil, fmt.Errorf("no row context for column: %s", ref.Column)
  4885. }
  4886. // For qualified column references (table.column):
  4887. //
  4888. // Resolution order:
  4889. // 1. Exact qualified key in outer row ("t1.b" → outer)
  4890. // 2. Case-insensitive qualified in outer row
  4891. // 3. Exact qualified key in current row ("x.b" → inner alias)
  4892. // 4. Case-insensitive qualified in current row
  4893. // 5. Unqualified in outer row — only reached when qualified lookup in current
  4894. // row failed, meaning the qualifier refers to an outer table not the inner
  4895. // alias (e.g. "t1.b" in a subquery "FROM t1 AS x" resolves here).
  4896. // 6. Unqualified in current row (last resort)
  4897. if ref.Table != "" {
  4898. if e.outerRow != nil {
  4899. // Step 1-2: qualified lookup in outer row
  4900. if val, ok := e.outerRow[ref.Table+"."+ref.Column]; ok {
  4901. return val, nil
  4902. }
  4903. for k, v := range e.outerRow {
  4904. if strings.EqualFold(k, ref.Table+"."+ref.Column) {
  4905. return v, nil
  4906. }
  4907. }
  4908. }
  4909. // Step 3-4: qualified lookup in current row
  4910. if val, ok := row[ref.Table+"."+ref.Column]; ok {
  4911. return val, nil
  4912. }
  4913. for k, v := range row {
  4914. if strings.EqualFold(k, ref.Table+"."+ref.Column) {
  4915. return v, nil
  4916. }
  4917. }
  4918. // Step 5: qualified lookup failed in current row — try outer row unqualified.
  4919. // This handles correlated subqueries where the qualifier names an outer table
  4920. // (e.g. "t1.b" when the inner FROM is "t1 AS x", so current row has "x.b"
  4921. // but no "t1.b").
  4922. if e.outerRow != nil {
  4923. if val, ok := e.outerRow[ref.Column]; ok {
  4924. return val, nil
  4925. }
  4926. for k, v := range e.outerRow {
  4927. if strings.EqualFold(k, ref.Column) {
  4928. return v, nil
  4929. }
  4930. }
  4931. }
  4932. }
  4933. // Step 6: unqualified fallback in current row (handles unqualified refs and
  4934. // single-table queries like "SELECT t1.a FROM t1" where rows have plain keys).
  4935. if val, ok := row[ref.Column]; ok {
  4936. return val, nil
  4937. }
  4938. for k, v := range row {
  4939. if strings.EqualFold(k, ref.Column) {
  4940. return v, nil
  4941. }
  4942. }
  4943. // For unqualified refs with an outer row context (ref.Table == "").
  4944. if e.outerRow != nil && ref.Table == "" {
  4945. if val, ok := e.outerRow[ref.Column]; ok {
  4946. return val, nil
  4947. }
  4948. for k, v := range e.outerRow {
  4949. if strings.EqualFold(k, ref.Column) {
  4950. return v, nil
  4951. }
  4952. }
  4953. }
  4954. // Hidden rowid alias (rowid/oid/_rowid_): only used when the row carries no
  4955. // real column of that name. SQLite semantics give an explicit column named
  4956. // oid/rowid/_rowid_ precedence over the hidden rowid alias, so this fallback
  4957. // runs last.
  4958. if storage.IsRowIDColumn(ref.Column) {
  4959. if val, ok := row["_rowid_"]; ok {
  4960. return val, nil
  4961. }
  4962. }
  4963. return nil, nil // Column not found, return NULL
  4964. }
  4965. func (e *Executor) evalBinaryExpr(expr *parser.BinaryExpr, row storage.Row) (interface{}, error) {
  4966. left, err := e.evalExpr(expr.Left, row)
  4967. if err != nil {
  4968. return nil, err
  4969. }
  4970. right, err := e.evalExpr(expr.Right, row)
  4971. if err != nil {
  4972. return nil, err
  4973. }
  4974. if isComparisonOp(expr.Op) {
  4975. left, right, err = e.canonicalizeArrayComparison(expr.Left, expr.Right, left, right)
  4976. if err != nil {
  4977. return nil, err
  4978. }
  4979. }
  4980. if isBitwiseOp(expr.Op) {
  4981. if left == nil || right == nil {
  4982. return nil, nil
  4983. }
  4984. return applyBitwise(expr.Op, left, right)
  4985. }
  4986. if expr.Op == lexer.TokenArrow || expr.Op == lexer.TokenArrowText {
  4987. return jsonArrowExtract(left, right, expr.Op == lexer.TokenArrowText)
  4988. }
  4989. switch expr.Op {
  4990. case lexer.TokenPlus:
  4991. if left == nil || right == nil {
  4992. return nil, nil
  4993. }
  4994. if isIntVal(left) && isIntVal(right) {
  4995. return toInt64(left) + toInt64(right), nil
  4996. }
  4997. return toFloat(left) + toFloat(right), nil
  4998. case lexer.TokenMinus:
  4999. if left == nil || right == nil {
  5000. return nil, nil
  5001. }
  5002. if isIntVal(left) && isIntVal(right) {
  5003. return toInt64(left) - toInt64(right), nil
  5004. }
  5005. return toFloat(left) - toFloat(right), nil
  5006. case lexer.TokenStar:
  5007. if left == nil || right == nil {
  5008. return nil, nil
  5009. }
  5010. if isIntVal(left) && isIntVal(right) {
  5011. return toInt64(left) * toInt64(right), nil
  5012. }
  5013. return toFloat(left) * toFloat(right), nil
  5014. case lexer.TokenSlash:
  5015. if left == nil || right == nil {
  5016. return nil, nil
  5017. }
  5018. // Integer division when both operands are integers (truncates toward zero, matching SQLite)
  5019. if isIntVal(left) && isIntVal(right) {
  5020. ri := toInt64(right)
  5021. if ri == 0 {
  5022. return nil, nil
  5023. }
  5024. return toInt64(left) / ri, nil
  5025. }
  5026. r := toFloat(right)
  5027. if r == 0 {
  5028. return nil, nil // Division by zero returns NULL
  5029. }
  5030. return toFloat(left) / r, nil
  5031. case lexer.TokenPercent:
  5032. if left == nil || right == nil {
  5033. return nil, nil
  5034. }
  5035. if isIntVal(left) && isIntVal(right) {
  5036. ri := toInt64(right)
  5037. if ri == 0 {
  5038. return nil, nil
  5039. }
  5040. return toInt64(left) % ri, nil
  5041. }
  5042. return int64(toFloat(left)) % int64(toFloat(right)), nil
  5043. case lexer.TokenEq:
  5044. if left == nil || right == nil {
  5045. return nil, nil
  5046. }
  5047. return compare(left, right) == 0, nil
  5048. case lexer.TokenNeq:
  5049. if left == nil || right == nil {
  5050. return nil, nil
  5051. }
  5052. return compare(left, right) != 0, nil
  5053. case lexer.TokenLt:
  5054. if left == nil || right == nil {
  5055. return nil, nil
  5056. }
  5057. return compare(left, right) < 0, nil
  5058. case lexer.TokenLte:
  5059. if left == nil || right == nil {
  5060. return nil, nil
  5061. }
  5062. return compare(left, right) <= 0, nil
  5063. case lexer.TokenGt:
  5064. if left == nil || right == nil {
  5065. return nil, nil
  5066. }
  5067. return compare(left, right) > 0, nil
  5068. case lexer.TokenGte:
  5069. if left == nil || right == nil {
  5070. return nil, nil
  5071. }
  5072. return compare(left, right) >= 0, nil
  5073. case lexer.TokenAND:
  5074. // Three-value logic: FALSE AND x = FALSE; NULL AND TRUE = NULL; TRUE AND TRUE = TRUE
  5075. if left != nil && !toBool(left) {
  5076. return false, nil
  5077. }
  5078. if right != nil && !toBool(right) {
  5079. return false, nil
  5080. }
  5081. if left == nil || right == nil {
  5082. return nil, nil
  5083. }
  5084. return true, nil
  5085. case lexer.TokenOR:
  5086. // Three-value logic: TRUE OR x = TRUE; NULL OR FALSE = NULL; FALSE OR FALSE = FALSE
  5087. if left != nil && toBool(left) {
  5088. return true, nil
  5089. }
  5090. if right != nil && toBool(right) {
  5091. return true, nil
  5092. }
  5093. if left == nil || right == nil {
  5094. return nil, nil
  5095. }
  5096. return false, nil
  5097. case lexer.TokenConcat:
  5098. return toString(left) + toString(right), nil
  5099. default:
  5100. return nil, fmt.Errorf("unsupported operator: %v", expr.Op)
  5101. }
  5102. }
  5103. // applyBinaryOp applies a binary operator to two already-evaluated values.
  5104. func (e *Executor) applyBinaryOp(op lexer.TokenType, left, right interface{}) (interface{}, error) {
  5105. if isBitwiseOp(op) {
  5106. if left == nil || right == nil {
  5107. return nil, nil
  5108. }
  5109. return applyBitwise(op, left, right)
  5110. }
  5111. if op == lexer.TokenArrow || op == lexer.TokenArrowText {
  5112. return jsonArrowExtract(left, right, op == lexer.TokenArrowText)
  5113. }
  5114. switch op {
  5115. case lexer.TokenPlus:
  5116. if left == nil || right == nil {
  5117. return nil, nil
  5118. }
  5119. if isIntVal(left) && isIntVal(right) {
  5120. return toInt64(left) + toInt64(right), nil
  5121. }
  5122. return toFloat(left) + toFloat(right), nil
  5123. case lexer.TokenMinus:
  5124. if left == nil || right == nil {
  5125. return nil, nil
  5126. }
  5127. if isIntVal(left) && isIntVal(right) {
  5128. return toInt64(left) - toInt64(right), nil
  5129. }
  5130. return toFloat(left) - toFloat(right), nil
  5131. case lexer.TokenStar:
  5132. if left == nil || right == nil {
  5133. return nil, nil
  5134. }
  5135. if isIntVal(left) && isIntVal(right) {
  5136. return toInt64(left) * toInt64(right), nil
  5137. }
  5138. return toFloat(left) * toFloat(right), nil
  5139. case lexer.TokenSlash:
  5140. if left == nil || right == nil {
  5141. return nil, nil
  5142. }
  5143. if isIntVal(left) && isIntVal(right) {
  5144. ri := toInt64(right)
  5145. if ri == 0 {
  5146. return nil, nil
  5147. }
  5148. return toInt64(left) / ri, nil
  5149. }
  5150. r := toFloat(right)
  5151. if r == 0 {
  5152. return nil, nil
  5153. }
  5154. return toFloat(left) / r, nil
  5155. case lexer.TokenPercent:
  5156. if left == nil || right == nil {
  5157. return nil, nil
  5158. }
  5159. if isIntVal(left) && isIntVal(right) {
  5160. ri := toInt64(right)
  5161. if ri == 0 {
  5162. return nil, nil
  5163. }
  5164. return toInt64(left) % ri, nil
  5165. }
  5166. return int64(toFloat(left)) % int64(toFloat(right)), nil
  5167. case lexer.TokenEq:
  5168. if left == nil || right == nil {
  5169. return nil, nil
  5170. }
  5171. return compare(left, right) == 0, nil
  5172. case lexer.TokenNeq:
  5173. if left == nil || right == nil {
  5174. return nil, nil
  5175. }
  5176. return compare(left, right) != 0, nil
  5177. case lexer.TokenLt:
  5178. if left == nil || right == nil {
  5179. return nil, nil
  5180. }
  5181. return compare(left, right) < 0, nil
  5182. case lexer.TokenLte:
  5183. if left == nil || right == nil {
  5184. return nil, nil
  5185. }
  5186. return compare(left, right) <= 0, nil
  5187. case lexer.TokenGt:
  5188. if left == nil || right == nil {
  5189. return nil, nil
  5190. }
  5191. return compare(left, right) > 0, nil
  5192. case lexer.TokenGte:
  5193. if left == nil || right == nil {
  5194. return nil, nil
  5195. }
  5196. return compare(left, right) >= 0, nil
  5197. case lexer.TokenAND:
  5198. if left != nil && !toBool(left) {
  5199. return false, nil
  5200. }
  5201. if right != nil && !toBool(right) {
  5202. return false, nil
  5203. }
  5204. if left == nil || right == nil {
  5205. return nil, nil
  5206. }
  5207. return true, nil
  5208. case lexer.TokenOR:
  5209. if left != nil && toBool(left) {
  5210. return true, nil
  5211. }
  5212. if right != nil && toBool(right) {
  5213. return true, nil
  5214. }
  5215. if left == nil || right == nil {
  5216. return nil, nil
  5217. }
  5218. return false, nil
  5219. case lexer.TokenConcat:
  5220. return toString(left) + toString(right), nil
  5221. default:
  5222. return nil, fmt.Errorf("unsupported operator: %v", op)
  5223. }
  5224. }
  5225. // isComparisonOp reports whether op compares two values.
  5226. func isComparisonOp(op lexer.TokenType) bool {
  5227. switch op {
  5228. case lexer.TokenEq, lexer.TokenNeq, lexer.TokenLt, lexer.TokenLte, lexer.TokenGt, lexer.TokenGte:
  5229. return true
  5230. }
  5231. return false
  5232. }
  5233. // isBitwiseOp reports whether op is a SQLite bitwise operator.
  5234. func isBitwiseOp(op lexer.TokenType) bool {
  5235. switch op {
  5236. case lexer.TokenBitAnd, lexer.TokenBitOr, lexer.TokenShiftLeft, lexer.TokenShiftRight:
  5237. return true
  5238. }
  5239. return false
  5240. }
  5241. // applyBitwise applies a bitwise operator with SQLite semantics. Operands are
  5242. // coerced to integers; a negative shift reverses direction, and an
  5243. // out-of-range shift saturates.
  5244. func applyBitwise(op lexer.TokenType, left, right interface{}) (interface{}, error) {
  5245. li := toInt64(left)
  5246. ri := toInt64(right)
  5247. switch op {
  5248. case lexer.TokenBitAnd:
  5249. return li & ri, nil
  5250. case lexer.TokenBitOr:
  5251. return li | ri, nil
  5252. case lexer.TokenShiftLeft:
  5253. return bitShiftLeft(li, ri), nil
  5254. case lexer.TokenShiftRight:
  5255. return bitShiftRight(li, ri), nil
  5256. default:
  5257. return nil, fmt.Errorf("unsupported bitwise operator: %v", op)
  5258. }
  5259. }
  5260. func bitShiftLeft(v, shift int64) int64 {
  5261. if shift < 0 {
  5262. return bitShiftRight(v, -shift)
  5263. }
  5264. if shift >= 64 {
  5265. return 0
  5266. }
  5267. return v << uint(shift)
  5268. }
  5269. func bitShiftRight(v, shift int64) int64 {
  5270. if shift < 0 {
  5271. return bitShiftLeft(v, -shift)
  5272. }
  5273. if shift >= 64 {
  5274. if v < 0 {
  5275. return -1
  5276. }
  5277. return 0
  5278. }
  5279. return v >> uint(shift)
  5280. }
  5281. // evalBuiltinFunction applies a named scalar function to pre-evaluated args.
  5282. func (e *Executor) evalBuiltinFunction(name string, args []interface{}) (interface{}, error) {
  5283. switch name {
  5284. case "NULLIF":
  5285. if len(args) >= 2 && compare(args[0], args[1]) == 0 {
  5286. return nil, nil
  5287. }
  5288. if len(args) > 0 {
  5289. return args[0], nil
  5290. }
  5291. case "IFNULL", "NVL":
  5292. if len(args) >= 2 {
  5293. if args[0] == nil {
  5294. return args[1], nil
  5295. }
  5296. return args[0], nil
  5297. }
  5298. case "COALESCE":
  5299. for _, a := range args {
  5300. if a != nil {
  5301. return a, nil
  5302. }
  5303. }
  5304. return nil, nil
  5305. case "ABS":
  5306. if len(args) > 0 && args[0] != nil {
  5307. if isIntVal(args[0]) {
  5308. v := toInt64(args[0])
  5309. if v < 0 {
  5310. return -v, nil
  5311. }
  5312. return v, nil
  5313. }
  5314. v := toFloat(args[0])
  5315. if v < 0 {
  5316. return -v, nil
  5317. }
  5318. return v, nil
  5319. }
  5320. case "LENGTH":
  5321. if len(args) > 0 && args[0] != nil {
  5322. return int64(len(fmt.Sprintf("%v", args[0]))), nil
  5323. }
  5324. }
  5325. // Fall back: store pre-evaluated values in row and build column refs.
  5326. row := make(storage.Row, len(args))
  5327. fn := &parser.FunctionCall{Name: name}
  5328. for i, a := range args {
  5329. key := fmt.Sprintf("__arg%d__", i)
  5330. row[key] = a
  5331. fn.Args = append(fn.Args, &parser.ColumnRef{Column: key})
  5332. }
  5333. return e.evalFunctionCall(fn, row)
  5334. }
  5335. func (e *Executor) evalUnaryExpr(expr *parser.UnaryExpr, row storage.Row) (interface{}, error) {
  5336. val, err := e.evalExpr(expr.Operand, row)
  5337. if err != nil {
  5338. return nil, err
  5339. }
  5340. switch expr.Op {
  5341. case lexer.TokenMinus:
  5342. if val == nil {
  5343. return nil, nil
  5344. }
  5345. if isIntVal(val) {
  5346. return -toInt64(val), nil
  5347. }
  5348. return -toFloat(val), nil
  5349. case lexer.TokenPlus:
  5350. if val == nil {
  5351. return nil, nil
  5352. }
  5353. if isIntVal(val) {
  5354. return toInt64(val), nil
  5355. }
  5356. return toFloat(val), nil
  5357. case lexer.TokenNOT:
  5358. if val == nil {
  5359. return nil, nil // NOT NULL = NULL
  5360. }
  5361. return !toBool(val), nil
  5362. case lexer.TokenBitNot:
  5363. if val == nil {
  5364. return nil, nil
  5365. }
  5366. return ^toInt64(val), nil
  5367. default:
  5368. return val, nil
  5369. }
  5370. }
  5371. func (e *Executor) evalFunctionCall(fn *parser.FunctionCall, row storage.Row) (interface{}, error) {
  5372. name := strings.ToUpper(fn.Name)
  5373. // Evaluate arguments
  5374. args := make([]interface{}, len(fn.Args))
  5375. for i, arg := range fn.Args {
  5376. val, err := e.evalExpr(arg, row)
  5377. if err != nil {
  5378. return nil, err
  5379. }
  5380. args[i] = val
  5381. }
  5382. // JSON1 scalar functions are dispatched separately to keep this switch tidy.
  5383. if val, handled, err := evalJSONFunction(name, args); handled {
  5384. return val, err
  5385. }
  5386. switch name {
  5387. case "UPPER":
  5388. if len(args) > 0 {
  5389. if args[0] == nil {
  5390. return nil, nil // NULL propagation
  5391. }
  5392. return strings.ToUpper(toString(args[0])), nil
  5393. }
  5394. case "LOWER":
  5395. if len(args) > 0 {
  5396. if args[0] == nil {
  5397. return nil, nil // NULL propagation
  5398. }
  5399. return strings.ToLower(toString(args[0])), nil
  5400. }
  5401. case "LENGTH":
  5402. if len(args) > 0 {
  5403. if args[0] == nil {
  5404. return nil, nil // NULL propagation
  5405. }
  5406. return int64(len(toString(args[0]))), nil
  5407. }
  5408. case "ABS":
  5409. if len(args) > 0 {
  5410. if args[0] == nil {
  5411. return nil, nil
  5412. }
  5413. v := toFloat(args[0])
  5414. if v < 0 {
  5415. return -v, nil
  5416. }
  5417. return v, nil
  5418. }
  5419. case "COALESCE":
  5420. for _, arg := range args {
  5421. if arg != nil {
  5422. return arg, nil
  5423. }
  5424. }
  5425. return nil, nil
  5426. case "NULLIF":
  5427. if len(args) >= 2 && compare(args[0], args[1]) == 0 {
  5428. return nil, nil
  5429. }
  5430. if len(args) > 0 {
  5431. return args[0], nil
  5432. }
  5433. case "IFNULL":
  5434. if len(args) >= 2 {
  5435. if args[0] == nil {
  5436. return args[1], nil
  5437. }
  5438. return args[0], nil
  5439. }
  5440. case "TYPEOF":
  5441. if len(args) > 0 {
  5442. switch args[0].(type) {
  5443. case nil:
  5444. return "null", nil
  5445. case int64, int:
  5446. return "integer", nil
  5447. case float64:
  5448. return "real", nil
  5449. case string:
  5450. return "text", nil
  5451. case []byte:
  5452. return "blob", nil
  5453. default:
  5454. return "text", nil
  5455. }
  5456. }
  5457. case "SUBSTR", "SUBSTRING":
  5458. if len(args) >= 2 {
  5459. // SQLite substring semantics. Indices are 1-based and inclusive:
  5460. // a zero or negative Y shifts the window rather than simply
  5461. // clamping, e.g. substr('US-NY', 0, 3) is 'US', not 'US-'.
  5462. runes := []rune(toString(args[0]))
  5463. n := len(runes)
  5464. y := int(toFloat(args[1]))
  5465. var start1, end1 int
  5466. switch {
  5467. case y < 0:
  5468. start1 = n + y + 1
  5469. case y == 0:
  5470. start1 = 1
  5471. default:
  5472. start1 = y
  5473. }
  5474. if len(args) >= 3 {
  5475. z := int(toFloat(args[2]))
  5476. switch {
  5477. case z < 0:
  5478. end1 = start1 - 1
  5479. start1 = end1 + z + 1
  5480. case y < 0:
  5481. end1 = start1 + z - 1
  5482. case y == 0:
  5483. end1 = z - 1
  5484. default:
  5485. end1 = y + z - 1
  5486. }
  5487. } else {
  5488. end1 = n
  5489. }
  5490. if start1 < 1 {
  5491. start1 = 1
  5492. }
  5493. if end1 > n {
  5494. end1 = n
  5495. }
  5496. if start1 > n || start1 > end1 {
  5497. return "", nil
  5498. }
  5499. return string(runes[start1-1 : end1]), nil
  5500. }
  5501. case "TRIM":
  5502. if len(args) > 0 {
  5503. return strings.TrimSpace(toString(args[0])), nil
  5504. }
  5505. case "REPLACE":
  5506. if len(args) >= 3 {
  5507. return strings.ReplaceAll(toString(args[0]), toString(args[1]), toString(args[2])), nil
  5508. }
  5509. // Additional SQLite functions
  5510. case "PRINTF":
  5511. if len(args) > 0 {
  5512. format := toString(args[0])
  5513. fmtArgs := make([]interface{}, len(args)-1)
  5514. for i := 1; i < len(args); i++ {
  5515. fmtArgs[i-1] = args[i]
  5516. }
  5517. return fmt.Sprintf(format, fmtArgs...), nil
  5518. }
  5519. case "HEX":
  5520. if len(args) > 0 {
  5521. if args[0] == nil {
  5522. return nil, nil
  5523. }
  5524. if b, ok := args[0].([]byte); ok {
  5525. return strings.ToUpper(fmt.Sprintf("%x", b)), nil
  5526. }
  5527. return strings.ToUpper(fmt.Sprintf("%x", []byte(toString(args[0])))), nil
  5528. }
  5529. case "UNHEX":
  5530. if len(args) > 0 {
  5531. if args[0] == nil {
  5532. return nil, nil
  5533. }
  5534. s := toString(args[0])
  5535. result, err := hex.DecodeString(strings.TrimSpace(s))
  5536. if err != nil {
  5537. return nil, nil
  5538. }
  5539. return result, nil
  5540. }
  5541. case "RANDOM":
  5542. return rand.Int63(), nil
  5543. case "RANDOMBLOB":
  5544. if len(args) > 0 {
  5545. n := int(toFloat(args[0]))
  5546. if n <= 0 {
  5547. n = 1
  5548. }
  5549. if n > 1000000 {
  5550. n = 1000000
  5551. }
  5552. blob := make([]byte, n)
  5553. rand.Read(blob)
  5554. return blob, nil
  5555. }
  5556. case "ZEROBLOB":
  5557. if len(args) > 0 {
  5558. n := int(toFloat(args[0]))
  5559. if n <= 0 {
  5560. n = 1
  5561. }
  5562. if n > 1000000 {
  5563. n = 1000000
  5564. }
  5565. return make([]byte, n), nil
  5566. }
  5567. case "INSTR":
  5568. if len(args) >= 2 {
  5569. s := toString(args[0])
  5570. substr := toString(args[1])
  5571. idx := strings.Index(s, substr)
  5572. if idx < 0 {
  5573. return int64(0), nil
  5574. }
  5575. return int64(idx + 1), nil // SQL is 1-indexed
  5576. }
  5577. case "GLOB":
  5578. if len(args) >= 2 {
  5579. pattern := toString(args[0])
  5580. s := toString(args[1])
  5581. return matchGlob(pattern, s), nil
  5582. }
  5583. case "ROUND":
  5584. if len(args) > 0 {
  5585. v := toFloat(args[0])
  5586. decimals := 0
  5587. if len(args) >= 2 {
  5588. decimals = int(toFloat(args[1]))
  5589. }
  5590. mult := 1.0
  5591. for i := 0; i < decimals; i++ {
  5592. mult *= 10
  5593. }
  5594. return float64(int64(v*mult+0.5)) / mult, nil
  5595. }
  5596. case "MAX":
  5597. if len(args) > 0 {
  5598. max := args[0]
  5599. for _, arg := range args[1:] {
  5600. if compare(arg, max) > 0 {
  5601. max = arg
  5602. }
  5603. }
  5604. return max, nil
  5605. }
  5606. case "MIN":
  5607. if len(args) > 0 {
  5608. min := args[0]
  5609. for _, arg := range args[1:] {
  5610. if compare(arg, min) < 0 {
  5611. min = arg
  5612. }
  5613. }
  5614. return min, nil
  5615. }
  5616. case "CONCAT":
  5617. var result strings.Builder
  5618. for _, arg := range args {
  5619. result.WriteString(toString(arg))
  5620. }
  5621. return result.String(), nil
  5622. case "CONCAT_WS":
  5623. // PostgreSQL semantics: a NULL separator yields NULL; NULL arguments are
  5624. // skipped rather than converted to empty strings.
  5625. if len(args) == 0 || args[0] == nil {
  5626. return nil, nil
  5627. }
  5628. separator := toString(args[0])
  5629. parts := make([]string, 0, len(args)-1)
  5630. for _, arg := range args[1:] {
  5631. if arg != nil {
  5632. parts = append(parts, toString(arg))
  5633. }
  5634. }
  5635. return strings.Join(parts, separator), nil
  5636. // Date/Time functions
  5637. case "DATE":
  5638. return evalDateFunc(args)
  5639. case "TIME":
  5640. return evalTimeFunc(args)
  5641. case "DATETIME":
  5642. return evalDatetimeFunc(args)
  5643. case "JULIANDAY":
  5644. return evalJuliandayFunc(args)
  5645. case "UNIXEPOCH":
  5646. return evalUnixepochFunc(args)
  5647. case "STRFTIME":
  5648. return evalStrftimeFunc(args)
  5649. case "TIMEDIFF":
  5650. return evalTimediffFunc(args)
  5651. case "PERCENT_DIFF":
  5652. return evalPercentDiff(args)
  5653. case "ARRAY_LENGTH":
  5654. if len(fn.Args) != 2 {
  5655. return nil, fmt.Errorf("array_length requires two arguments")
  5656. }
  5657. return e.evalArrayLength(fn.Args[0], args)
  5658. case "UNNEST":
  5659. return nil, pgerror.Unsupported("unnest() is only supported as a table function in FROM, as in SELECT * FROM unnest(array)")
  5660. case "PIZZASQL_VERSION":
  5661. return version.String(), nil
  5662. case "SQLITE_VERSION":
  5663. return SQLiteCompatVersion, nil
  5664. case "LAST_INSERT_ROWID":
  5665. return e.lastInsertRowID, nil
  5666. case "PG_BACKEND_PID":
  5667. return int64(e.backendPID), nil
  5668. case "CHANGES":
  5669. return e.changes, nil
  5670. case "TOTAL_CHANGES":
  5671. return e.totalChanges, nil
  5672. }
  5673. return nil, nil
  5674. }
  5675. func (e *Executor) evalCaseExpr(expr *parser.CaseExpr, row storage.Row) (interface{}, error) {
  5676. var operand interface{}
  5677. if expr.Operand != nil {
  5678. var err error
  5679. operand, err = e.evalExpr(expr.Operand, row)
  5680. if err != nil {
  5681. return nil, err
  5682. }
  5683. }
  5684. for _, when := range expr.Whens {
  5685. cond, err := e.evalExpr(when.Condition, row)
  5686. if err != nil {
  5687. return nil, err
  5688. }
  5689. var match bool
  5690. if expr.Operand != nil {
  5691. // Simple CASE: CASE operand WHEN val THEN ... — NULL operand matches nothing
  5692. if operand == nil {
  5693. continue
  5694. }
  5695. match = compare(operand, cond) == 0
  5696. } else {
  5697. // Searched CASE: CASE WHEN cond THEN ... — NULL condition is falsy
  5698. match = toBool(cond)
  5699. }
  5700. if match {
  5701. return e.evalExpr(when.Result, row)
  5702. }
  5703. }
  5704. if expr.Else != nil {
  5705. return e.evalExpr(expr.Else, row)
  5706. }
  5707. return nil, nil
  5708. }
  5709. func (e *Executor) evalInExpr(expr *parser.InExpr, row storage.Row) (interface{}, error) {
  5710. left, err := e.evalExpr(expr.Left, row)
  5711. if err != nil {
  5712. return nil, err
  5713. }
  5714. // Handle subquery: IN (SELECT ...)
  5715. if expr.Subquery != nil {
  5716. var result *Result
  5717. var err error
  5718. // Cache non-correlated subquery results for the duration of this query.
  5719. // Safe when outerRow is nil (no outer context that the subquery could reference).
  5720. if e.subqueryCache != nil && e.outerRow == nil {
  5721. if cached, ok := e.subqueryCache[expr.Subquery]; ok {
  5722. result = cached
  5723. } else {
  5724. result, err = e.executeSelect(expr.Subquery)
  5725. if err == nil {
  5726. e.subqueryCache[expr.Subquery] = result
  5727. }
  5728. }
  5729. } else {
  5730. result, err = e.executeSelect(expr.Subquery)
  5731. }
  5732. if err != nil {
  5733. return nil, fmt.Errorf("IN subquery error: %w", err)
  5734. }
  5735. if len(result.Columns) != 1 {
  5736. return nil, fmt.Errorf("subquery in IN must return exactly one column")
  5737. }
  5738. // SQL three-valued logic: if left is NULL → NULL; if any match → true; if any NULL → NULL; else false.
  5739. if left == nil {
  5740. return nil, nil
  5741. }
  5742. sawNull := false
  5743. for _, resultRow := range result.Rows {
  5744. if len(resultRow) == 0 {
  5745. continue
  5746. }
  5747. v := resultRow[0]
  5748. if v == nil {
  5749. sawNull = true
  5750. continue
  5751. }
  5752. v, canonErr := e.canonicalArrayValue(expr.Left, v)
  5753. if canonErr != nil {
  5754. return nil, canonErr
  5755. }
  5756. if compare(left, v) == 0 {
  5757. if expr.Not {
  5758. return false, nil
  5759. }
  5760. return true, nil
  5761. }
  5762. }
  5763. if sawNull {
  5764. return nil, nil
  5765. }
  5766. if expr.Not {
  5767. return true, nil
  5768. }
  5769. return false, nil
  5770. }
  5771. // Handle value list: IN (1, 2, 3).
  5772. // Empty list: always FALSE (IN) / TRUE (NOT IN), even for NULL.
  5773. if len(expr.Values) == 0 {
  5774. return expr.Not, nil
  5775. }
  5776. // SQL three-valued logic: if left is NULL → NULL; if any match → true/false;
  5777. // if list contains NULL and no match → NULL.
  5778. if left == nil {
  5779. return nil, nil
  5780. }
  5781. sawNull := false
  5782. for _, val := range expr.Values {
  5783. v, err := e.evalExpr(val, row)
  5784. if err != nil {
  5785. return nil, err
  5786. }
  5787. if v == nil {
  5788. sawNull = true
  5789. continue
  5790. }
  5791. v, err = e.canonicalArrayValue(expr.Left, v)
  5792. if err != nil {
  5793. return nil, err
  5794. }
  5795. if compare(left, v) == 0 {
  5796. if expr.Not {
  5797. return false, nil
  5798. }
  5799. return true, nil
  5800. }
  5801. }
  5802. if sawNull {
  5803. return nil, nil
  5804. }
  5805. if expr.Not {
  5806. return true, nil
  5807. }
  5808. return false, nil
  5809. }
  5810. func (e *Executor) evalBetweenExpr(expr *parser.BetweenExpr, row storage.Row) (interface{}, error) {
  5811. val, err := e.evalExpr(expr.Left, row)
  5812. if err != nil {
  5813. return nil, err
  5814. }
  5815. low, err := e.evalExpr(expr.Low, row)
  5816. if err != nil {
  5817. return nil, err
  5818. }
  5819. high, err := e.evalExpr(expr.High, row)
  5820. if err != nil {
  5821. return nil, err
  5822. }
  5823. if expr.Not {
  5824. // NOT BETWEEN is equivalent to: val < low OR val > high
  5825. // We need to handle NULL using three-valued OR logic:
  5826. // NULL OR TRUE = TRUE
  5827. // NULL OR FALSE = NULL
  5828. // NULL OR NULL = NULL
  5829. var lessThan, greaterThan interface{}
  5830. if val == nil || low == nil {
  5831. lessThan = nil // NULL
  5832. } else {
  5833. lessThan = compare(val, low) < 0
  5834. }
  5835. if val == nil || high == nil {
  5836. greaterThan = nil // NULL
  5837. } else {
  5838. greaterThan = compare(val, high) > 0
  5839. }
  5840. // Implement three-valued OR
  5841. if toBool(lessThan) || toBool(greaterThan) {
  5842. return true, nil
  5843. }
  5844. if lessThan == nil || greaterThan == nil {
  5845. return nil, nil // NULL
  5846. }
  5847. return false, nil
  5848. } else {
  5849. // BETWEEN is equivalent to: val >= low AND val <= high
  5850. // Three-value logic: if val < low → FALSE (regardless of high); if val >= low and high is NULL → NULL
  5851. if val == nil {
  5852. return nil, nil
  5853. }
  5854. // x BETWEEN a AND b = (x >= a) AND (x <= b)
  5855. // NULL AND FALSE = FALSE; NULL AND TRUE = NULL
  5856. if low == nil {
  5857. // x >= NULL = NULL; check upper bound for early FALSE
  5858. if high != nil && compare(val, high) > 0 {
  5859. return false, nil // NULL AND FALSE = FALSE
  5860. }
  5861. return nil, nil // NULL AND TRUE/NULL = NULL
  5862. }
  5863. if compare(val, low) < 0 {
  5864. return false, nil // val < low → FALSE AND anything = FALSE
  5865. }
  5866. if high == nil {
  5867. return nil, nil // TRUE AND NULL = NULL
  5868. }
  5869. return compare(val, high) <= 0, nil
  5870. }
  5871. }
  5872. func (e *Executor) evalLikeExpr(expr *parser.LikeExpr, row storage.Row) (interface{}, error) {
  5873. val, err := e.evalExpr(expr.Left, row)
  5874. if err != nil {
  5875. return nil, err
  5876. }
  5877. pattern, err := e.evalExpr(expr.Pattern, row)
  5878. if err != nil {
  5879. return nil, err
  5880. }
  5881. s := toString(val)
  5882. p := toString(pattern)
  5883. // Convert SQL LIKE pattern to simple matching
  5884. // % matches any sequence, _ matches single character
  5885. matched := matchLike(s, p)
  5886. if expr.Not {
  5887. return !matched, nil
  5888. }
  5889. return matched, nil
  5890. }
  5891. func (e *Executor) evalIsNullExpr(expr *parser.IsNullExpr, row storage.Row) (interface{}, error) {
  5892. val, err := e.evalExpr(expr.Left, row)
  5893. if err != nil {
  5894. return nil, err
  5895. }
  5896. isNull := val == nil
  5897. if expr.Not {
  5898. return !isNull, nil
  5899. }
  5900. return isNull, nil
  5901. }
  5902. // evalIsDistinctExpr implements `a IS [NOT] DISTINCT FROM b`. It treats NULL as a
  5903. // comparable value: two NULLs are not distinct, and NULL is distinct from any
  5904. // non-NULL.
  5905. func (e *Executor) evalIsDistinctExpr(expr *parser.IsDistinctExpr, row storage.Row) (interface{}, error) {
  5906. left, err := e.evalExpr(expr.Left, row)
  5907. if err != nil {
  5908. return nil, err
  5909. }
  5910. right, err := e.evalExpr(expr.Right, row)
  5911. if err != nil {
  5912. return nil, err
  5913. }
  5914. left, right, err = e.canonicalizeArrayComparison(expr.Left, expr.Right, left, right)
  5915. if err != nil {
  5916. return nil, err
  5917. }
  5918. distinct := false
  5919. switch {
  5920. case left == nil && right == nil:
  5921. distinct = false
  5922. case left == nil || right == nil:
  5923. distinct = true
  5924. default:
  5925. distinct = compare(left, right) != 0
  5926. }
  5927. if expr.Not {
  5928. return !distinct, nil
  5929. }
  5930. return distinct, nil
  5931. }
  5932. func (e *Executor) evalCastExpr(expr *parser.CastExpr, row storage.Row) (interface{}, error) {
  5933. val, err := e.evalExpr(expr.Expr, row)
  5934. if err != nil {
  5935. return nil, err
  5936. }
  5937. if val == nil {
  5938. return nil, nil // CAST(NULL AS any) = NULL
  5939. }
  5940. if expr.Type.Array {
  5941. return evalArrayCast(expr.Type, val)
  5942. }
  5943. typeName := strings.ToUpper(expr.Type.Name)
  5944. switch {
  5945. case strings.Contains(typeName, "INT"):
  5946. return int64(toFloat(val)), nil
  5947. case strings.Contains(typeName, "REAL"), strings.Contains(typeName, "FLOAT"), strings.Contains(typeName, "DOUBLE"):
  5948. return toFloat(val), nil
  5949. case strings.Contains(typeName, "BLOB"):
  5950. if b, ok := val.([]byte); ok {
  5951. return b, nil
  5952. }
  5953. return []byte(toString(val)), nil
  5954. case strings.Contains(typeName, "TEXT"), strings.Contains(typeName, "CHAR"):
  5955. return toString(val), nil
  5956. default:
  5957. return val, nil
  5958. }
  5959. }
  5960. // evalSubqueryExpr executes a scalar subquery and returns its value.
  5961. // A scalar subquery must return exactly one column. It returns:
  5962. // - The single value if the subquery returns one row
  5963. // - NULL if the subquery returns no rows
  5964. // - Error if the subquery returns more than one row (for strict SQL compliance)
  5965. func (e *Executor) evalSubqueryExpr(expr *parser.SubqueryExpr, row storage.Row) (interface{}, error) {
  5966. if row != nil && e.correlatedAggCache != nil {
  5967. if val, ok, err := e.evalDecorrelatedAggSubquery(expr.Query, row); ok || err != nil {
  5968. return val, err
  5969. }
  5970. }
  5971. // Save and set outer row context for correlated subqueries
  5972. savedOuter := e.outerRow
  5973. e.outerRow = row
  5974. defer func() { e.outerRow = savedOuter }()
  5975. // Execute the subquery
  5976. result, err := e.executeSelect(expr.Query)
  5977. if err != nil {
  5978. return nil, fmt.Errorf("subquery error: %w", err)
  5979. }
  5980. // Check for empty result
  5981. if result.RowCount == 0 {
  5982. return nil, nil // Return NULL for empty subquery
  5983. }
  5984. // Check column count
  5985. if len(result.Columns) == 0 {
  5986. return nil, fmt.Errorf("subquery must return at least one column")
  5987. }
  5988. // For scalar subquery, return first column of first row
  5989. // Note: Strict SQL would error if more than one row is returned
  5990. // but we follow SQLite behavior which just returns the first value
  5991. if len(result.Rows) > 0 && len(result.Rows[0]) > 0 {
  5992. return result.Rows[0][0], nil
  5993. }
  5994. return nil, nil
  5995. }
  5996. func (e *Executor) evalDecorrelatedAggSubquery(query *parser.SelectStmt, outerRow storage.Row) (interface{}, bool, error) {
  5997. spec, ok := e.correlatedAggSpec(query)
  5998. if !ok {
  5999. return nil, false, nil
  6000. }
  6001. outerVal, err := e.evalExpr(spec.outerKey, outerRow)
  6002. if err != nil {
  6003. return nil, true, err
  6004. }
  6005. cache, exists := e.correlatedAggCache[query]
  6006. if !exists {
  6007. cache, err = e.buildCorrelatedAggCache(query, spec)
  6008. if err != nil {
  6009. return nil, true, err
  6010. }
  6011. e.correlatedAggCache[query] = cache
  6012. }
  6013. if outerVal == nil {
  6014. return cache.defaultValue, true, nil
  6015. }
  6016. if val, exists := cache.values[fmt.Sprintf("%v", outerVal)]; exists {
  6017. return val, true, nil
  6018. }
  6019. return cache.defaultValue, true, nil
  6020. }
  6021. func (e *Executor) correlatedAggSpec(query *parser.SelectStmt) (correlatedAggSpec, bool) {
  6022. if query == nil ||
  6023. query.Compound != nil ||
  6024. len(query.Columns) != 1 ||
  6025. len(query.From) == 0 ||
  6026. query.Where == nil ||
  6027. len(query.GroupBy) > 0 ||
  6028. query.Having != nil ||
  6029. query.Limit != nil ||
  6030. query.Offset != nil {
  6031. return correlatedAggSpec{}, false
  6032. }
  6033. if query.Columns[0].Star {
  6034. return correlatedAggSpec{}, false
  6035. }
  6036. agg, ok := query.Columns[0].Expr.(*parser.FunctionCall)
  6037. if !ok {
  6038. return correlatedAggSpec{}, false
  6039. }
  6040. switch strings.ToUpper(agg.Name) {
  6041. case "COUNT", "SUM", "AVG", "MIN", "MAX":
  6042. default:
  6043. return correlatedAggSpec{}, false
  6044. }
  6045. innerAliases := collectFromAliases(query.From)
  6046. bin, ok := query.Where.(*parser.BinaryExpr)
  6047. if !ok || bin.Op != lexer.TokenEq {
  6048. return correlatedAggSpec{}, false
  6049. }
  6050. leftRef, leftIsRef := bin.Left.(*parser.ColumnRef)
  6051. rightRef, rightIsRef := bin.Right.(*parser.ColumnRef)
  6052. if !leftIsRef || !rightIsRef {
  6053. return correlatedAggSpec{}, false
  6054. }
  6055. leftInner := refBelongsToAliases(leftRef, innerAliases)
  6056. rightInner := refBelongsToAliases(rightRef, innerAliases)
  6057. if leftInner == rightInner {
  6058. return correlatedAggSpec{}, false
  6059. }
  6060. if leftInner {
  6061. return correlatedAggSpec{innerKey: leftRef, outerKey: rightRef, aggExpr: agg}, true
  6062. }
  6063. return correlatedAggSpec{innerKey: rightRef, outerKey: leftRef, aggExpr: agg}, true
  6064. }
  6065. func (e *Executor) buildCorrelatedAggCache(query *parser.SelectStmt, spec correlatedAggSpec) (*correlatedAggCache, error) {
  6066. grouped := *query
  6067. grouped.Where = nil
  6068. grouped.GroupBy = []parser.Expr{spec.innerKey}
  6069. grouped.Having = nil
  6070. grouped.OrderBy = nil
  6071. grouped.Limit = nil
  6072. grouped.Offset = nil
  6073. grouped.Columns = []parser.SelectColumn{
  6074. {Expr: spec.innerKey, Alias: "__corr_key"},
  6075. {Expr: spec.aggExpr, Alias: "__corr_value"},
  6076. }
  6077. savedOuter := e.outerRow
  6078. e.outerRow = nil
  6079. result, err := e.executeSelect(&grouped)
  6080. e.outerRow = savedOuter
  6081. if err != nil {
  6082. return nil, fmt.Errorf("decorrelated aggregate subquery error: %w", err)
  6083. }
  6084. cache := &correlatedAggCache{
  6085. values: make(map[string]interface{}, len(result.Rows)),
  6086. defaultValue: correlatedAggDefault(spec.aggExpr),
  6087. }
  6088. for _, row := range result.Rows {
  6089. if len(row) < 2 || row[0] == nil {
  6090. continue
  6091. }
  6092. cache.values[fmt.Sprintf("%v", row[0])] = row[1]
  6093. }
  6094. return cache, nil
  6095. }
  6096. func correlatedAggDefault(expr parser.Expr) interface{} {
  6097. if fn, ok := expr.(*parser.FunctionCall); ok && strings.EqualFold(fn.Name, "COUNT") {
  6098. return int64(0)
  6099. }
  6100. return nil
  6101. }
  6102. func collectFromAliases(from []parser.TableRef) map[string]struct{} {
  6103. aliases := make(map[string]struct{})
  6104. var addRef func(parser.TableRef)
  6105. addRef = func(ref parser.TableRef) {
  6106. if ref.Name != "" {
  6107. aliases[strings.ToLower(ref.Name)] = struct{}{}
  6108. }
  6109. if ref.Alias != "" {
  6110. aliases[strings.ToLower(ref.Alias)] = struct{}{}
  6111. }
  6112. if ref.Join != nil && ref.Join.Table != nil {
  6113. addRef(*ref.Join.Table)
  6114. }
  6115. }
  6116. for _, ref := range from {
  6117. addRef(ref)
  6118. }
  6119. return aliases
  6120. }
  6121. func refBelongsToAliases(ref *parser.ColumnRef, aliases map[string]struct{}) bool {
  6122. if ref == nil || ref.Table == "" {
  6123. return false
  6124. }
  6125. _, ok := aliases[strings.ToLower(ref.Table)]
  6126. return ok
  6127. }
  6128. // evalExistsExpr evaluates an EXISTS expression.
  6129. // Returns true if the subquery returns at least one row, false otherwise.
  6130. func (e *Executor) evalExistsExpr(expr *parser.ExistsExpr, row storage.Row) (interface{}, error) {
  6131. // Save and set outer row context for correlated subqueries
  6132. savedOuter := e.outerRow
  6133. e.outerRow = row
  6134. defer func() { e.outerRow = savedOuter }()
  6135. // Execute the subquery
  6136. result, err := e.executeSelect(expr.Subquery)
  6137. if err != nil {
  6138. return nil, fmt.Errorf("EXISTS subquery error: %w", err)
  6139. }
  6140. // EXISTS returns true if any rows are returned
  6141. return len(result.Rows) > 0, nil
  6142. }
  6143. // evalAggregateExpr evaluates an aggregate expression over multiple rows.
  6144. func (e *Executor) evalAggregateExpr(expr parser.Expr, rows []storage.Row) (interface{}, error) {
  6145. fn, ok := expr.(*parser.FunctionCall)
  6146. if !ok {
  6147. // Not a function call - could be a binary expression with aggregates inside
  6148. // Evaluate it with the aggregate evaluation context
  6149. return e.evalExprWithAggregates(expr, rows)
  6150. }
  6151. name := strings.ToUpper(fn.Name)
  6152. switch name {
  6153. case "COUNT":
  6154. if fn.Star {
  6155. return int64(len(rows)), nil
  6156. }
  6157. if fn.Distinct {
  6158. seen := make(map[interface{}]struct{})
  6159. for _, row := range rows {
  6160. if len(fn.Args) > 0 {
  6161. val, _ := e.evalExpr(fn.Args[0], row)
  6162. if val != nil {
  6163. seen[val] = struct{}{}
  6164. }
  6165. }
  6166. }
  6167. return int64(len(seen)), nil
  6168. }
  6169. count := int64(0)
  6170. for _, row := range rows {
  6171. if len(fn.Args) > 0 {
  6172. val, _ := e.evalExpr(fn.Args[0], row)
  6173. if val != nil {
  6174. count++
  6175. }
  6176. }
  6177. }
  6178. return count, nil
  6179. case "SUM":
  6180. var sumInt int64
  6181. var sumFloat float64
  6182. allInt := true
  6183. hasValues := false
  6184. var seen map[interface{}]struct{}
  6185. if fn.Distinct {
  6186. seen = make(map[interface{}]struct{})
  6187. }
  6188. for _, row := range rows {
  6189. if len(fn.Args) > 0 {
  6190. val, _ := e.evalExpr(fn.Args[0], row)
  6191. if val != nil {
  6192. if fn.Distinct {
  6193. key := fmt.Sprintf("%v", val)
  6194. if _, exists := seen[key]; exists {
  6195. continue
  6196. }
  6197. seen[key] = struct{}{}
  6198. }
  6199. if isIntVal(val) {
  6200. sumInt += toInt64(val)
  6201. } else {
  6202. allInt = false
  6203. sumFloat += toFloat(val)
  6204. }
  6205. hasValues = true
  6206. }
  6207. }
  6208. }
  6209. if !hasValues {
  6210. return nil, nil
  6211. }
  6212. if allInt {
  6213. return sumInt, nil
  6214. }
  6215. return sumFloat + float64(sumInt), nil
  6216. case "AVG":
  6217. var sum float64
  6218. count := 0
  6219. for _, row := range rows {
  6220. if len(fn.Args) > 0 {
  6221. val, _ := e.evalExpr(fn.Args[0], row)
  6222. if val != nil {
  6223. sum += toFloat(val)
  6224. count++
  6225. }
  6226. }
  6227. }
  6228. if count == 0 {
  6229. return nil, nil
  6230. }
  6231. return sum / float64(count), nil
  6232. case "MIN":
  6233. var min interface{}
  6234. for _, row := range rows {
  6235. if len(fn.Args) > 0 {
  6236. val, _ := e.evalExpr(fn.Args[0], row)
  6237. if val != nil && (min == nil || compare(val, min) < 0) {
  6238. min = val
  6239. }
  6240. }
  6241. }
  6242. return min, nil
  6243. case "MAX":
  6244. var max interface{}
  6245. for _, row := range rows {
  6246. if len(fn.Args) > 0 {
  6247. val, _ := e.evalExpr(fn.Args[0], row)
  6248. if val != nil && (max == nil || compare(val, max) > 0) {
  6249. max = val
  6250. }
  6251. }
  6252. }
  6253. return max, nil
  6254. case "TOTAL":
  6255. var sum float64
  6256. for _, row := range rows {
  6257. if len(fn.Args) > 0 {
  6258. val, _ := e.evalExpr(fn.Args[0], row)
  6259. if val != nil {
  6260. sum += toFloat(val)
  6261. }
  6262. }
  6263. }
  6264. return sum, nil
  6265. case "STRING_AGG":
  6266. if len(fn.Args) == 0 {
  6267. return nil, fmt.Errorf("STRING_AGG requires at least one argument")
  6268. }
  6269. separator := ""
  6270. if len(fn.Args) > 1 && len(rows) > 0 {
  6271. sep, err := e.evalExpr(fn.Args[1], rows[0])
  6272. if err != nil {
  6273. return nil, err
  6274. }
  6275. if sep == nil {
  6276. return nil, nil
  6277. }
  6278. separator = toString(sep)
  6279. }
  6280. var seen map[string]struct{}
  6281. if fn.Distinct {
  6282. seen = make(map[string]struct{})
  6283. }
  6284. var parts []string
  6285. for _, row := range rows {
  6286. val, err := e.evalExpr(fn.Args[0], row)
  6287. if err != nil {
  6288. return nil, err
  6289. }
  6290. if val == nil {
  6291. continue
  6292. }
  6293. text := toString(val)
  6294. if fn.Distinct {
  6295. if _, exists := seen[text]; exists {
  6296. continue
  6297. }
  6298. seen[text] = struct{}{}
  6299. }
  6300. parts = append(parts, text)
  6301. }
  6302. if len(parts) == 0 {
  6303. return nil, nil
  6304. }
  6305. return strings.Join(parts, separator), nil
  6306. case "GROUP_CONCAT":
  6307. if len(fn.Args) == 0 {
  6308. return nil, fmt.Errorf("GROUP_CONCAT requires at least one argument")
  6309. }
  6310. var seen map[string]struct{}
  6311. if fn.Distinct {
  6312. seen = make(map[string]struct{})
  6313. }
  6314. var builder strings.Builder
  6315. count := 0
  6316. for _, row := range rows {
  6317. val, err := e.evalExpr(fn.Args[0], row)
  6318. if err != nil {
  6319. return nil, err
  6320. }
  6321. if val == nil {
  6322. continue
  6323. }
  6324. text := toString(val)
  6325. if fn.Distinct {
  6326. if _, exists := seen[text]; exists {
  6327. continue
  6328. }
  6329. seen[text] = struct{}{}
  6330. }
  6331. if count > 0 {
  6332. separator := ","
  6333. if len(fn.Args) > 1 {
  6334. sep, err := e.evalExpr(fn.Args[1], row)
  6335. if err != nil {
  6336. return nil, err
  6337. }
  6338. separator = toString(sep)
  6339. }
  6340. builder.WriteString(separator)
  6341. }
  6342. builder.WriteString(text)
  6343. count++
  6344. }
  6345. if count == 0 {
  6346. return nil, nil
  6347. }
  6348. return builder.String(), nil
  6349. case "JSON_GROUP_ARRAY", "JSONB_GROUP_ARRAY":
  6350. arr := make([]interface{}, 0, len(rows))
  6351. var seen map[string]struct{}
  6352. if fn.Distinct {
  6353. seen = make(map[string]struct{})
  6354. }
  6355. for _, row := range rows {
  6356. var val interface{}
  6357. if len(fn.Args) > 0 {
  6358. val, _ = e.evalExpr(fn.Args[0], row)
  6359. }
  6360. if fn.Distinct {
  6361. key := fmt.Sprintf("%v", val)
  6362. if _, exists := seen[key]; exists {
  6363. continue
  6364. }
  6365. seen[key] = struct{}{}
  6366. }
  6367. arr = append(arr, jsonArgToNode(val))
  6368. }
  6369. s, err := jsonEncode(arr)
  6370. if err != nil {
  6371. return nil, err
  6372. }
  6373. return jsonText(s), nil
  6374. default:
  6375. if isAggregateCallName(name) {
  6376. return nil, fmt.Errorf("unsupported aggregate function: %s", name)
  6377. }
  6378. // Non-aggregate scalar function: evaluate args through aggregate context
  6379. // (so COUNT/MIN/etc. inside NULLIF/COALESCE work correctly).
  6380. return e.evalExprWithAggregates(expr, rows)
  6381. }
  6382. }
  6383. // isAggregateCallName lists the aggregate functions handled by
  6384. // evalAggregateExpr. Keeping dispatch and evaluation on the same list prevents
  6385. // an unhandled aggregate from recursing between the aggregate and expression
  6386. // evaluators.
  6387. func isAggregateCallName(name string) bool {
  6388. switch strings.ToUpper(name) {
  6389. case "COUNT", "SUM", "AVG", "MIN", "MAX", "TOTAL", "GROUP_CONCAT", "STRING_AGG",
  6390. "JSON_GROUP_ARRAY", "JSONB_GROUP_ARRAY":
  6391. return true
  6392. default:
  6393. return false
  6394. }
  6395. }
  6396. // evalExprWithAggregates evaluates an expression that may contain aggregate functions
  6397. func (e *Executor) evalExprWithAggregates(expr parser.Expr, rows []storage.Row) (interface{}, error) {
  6398. switch ex := expr.(type) {
  6399. case *parser.BinaryExpr:
  6400. left, err := e.evalExprWithAggregates(ex.Left, rows)
  6401. if err != nil {
  6402. return nil, err
  6403. }
  6404. right, err := e.evalExprWithAggregates(ex.Right, rows)
  6405. if err != nil {
  6406. return nil, err
  6407. }
  6408. if isComparisonOp(ex.Op) {
  6409. left, right, err = e.canonicalizeArrayComparison(ex.Left, ex.Right, left, right)
  6410. if err != nil {
  6411. return nil, err
  6412. }
  6413. }
  6414. // Use the same logic as evalBinaryExpr to preserve integer semantics.
  6415. combined := &parser.BinaryExpr{Op: ex.Op}
  6416. return e.applyBinaryOp(combined.Op, left, right)
  6417. case *parser.FunctionCall:
  6418. name := strings.ToUpper(ex.Name)
  6419. if isAggregateCallName(name) {
  6420. return e.evalAggregateExpr(expr, rows)
  6421. }
  6422. // Non-aggregate: evaluate each arg with aggregate context, then apply scalar.
  6423. args := make([]interface{}, len(ex.Args))
  6424. for i, arg := range ex.Args {
  6425. v, err := e.evalExprWithAggregates(arg, rows)
  6426. if err != nil {
  6427. return nil, err
  6428. }
  6429. args[i] = v
  6430. }
  6431. return e.evalBuiltinFunction(name, args)
  6432. case *parser.ParenExpr:
  6433. return e.evalExprWithAggregates(ex.Expr, rows)
  6434. case *parser.UnaryExpr:
  6435. operand, err := e.evalExprWithAggregates(ex.Operand, rows)
  6436. if err != nil {
  6437. return nil, err
  6438. }
  6439. switch ex.Op {
  6440. case lexer.TokenPlus:
  6441. return operand, nil
  6442. case lexer.TokenMinus:
  6443. if operand == nil {
  6444. return nil, nil
  6445. }
  6446. if isIntVal(operand) {
  6447. return -toInt64(operand), nil
  6448. }
  6449. return -toFloat(operand), nil
  6450. case lexer.TokenNOT:
  6451. if operand == nil {
  6452. return nil, nil // NOT NULL = NULL
  6453. }
  6454. return !toBool(operand), nil
  6455. default:
  6456. return nil, fmt.Errorf("unsupported unary operator: %v", ex.Op)
  6457. }
  6458. case *parser.CastExpr:
  6459. // Evaluate inner expression with aggregate context, then apply cast.
  6460. val, err := e.evalExprWithAggregates(ex.Expr, rows)
  6461. if err != nil {
  6462. return nil, err
  6463. }
  6464. if val == nil {
  6465. return nil, nil
  6466. }
  6467. if ex.Type.Array {
  6468. return evalArrayCast(ex.Type, val)
  6469. }
  6470. switch strings.ToUpper(ex.Type.Name) {
  6471. case "INTEGER", "INT", "BIGINT", "SMALLINT", "TINYINT", "SIGNED":
  6472. if isIntVal(val) {
  6473. return toInt64(val), nil
  6474. }
  6475. return int64(toFloat(val)), nil
  6476. case "REAL", "FLOAT", "DOUBLE", "NUMERIC", "DECIMAL":
  6477. return toFloat(val), nil
  6478. case "TEXT", "VARCHAR", "CHAR", "STRING":
  6479. return fmt.Sprintf("%v", val), nil
  6480. }
  6481. return val, nil
  6482. case *parser.CaseExpr:
  6483. var operand interface{}
  6484. if ex.Operand != nil {
  6485. operand, _ = e.evalExprWithAggregates(ex.Operand, rows)
  6486. }
  6487. for _, when := range ex.Whens {
  6488. condVal, _ := e.evalExprWithAggregates(when.Condition, rows)
  6489. var matched bool
  6490. if ex.Operand != nil {
  6491. matched = operand != nil && condVal != nil && compare(operand, condVal) == 0
  6492. } else {
  6493. matched = toBool(condVal)
  6494. }
  6495. if matched {
  6496. return e.evalExprWithAggregates(when.Result, rows)
  6497. }
  6498. }
  6499. if ex.Else != nil {
  6500. return e.evalExprWithAggregates(ex.Else, rows)
  6501. }
  6502. return nil, nil
  6503. case *parser.IsNullExpr:
  6504. val, err := e.evalExprWithAggregates(ex.Left, rows)
  6505. if err != nil {
  6506. return nil, err
  6507. }
  6508. isNull := val == nil
  6509. if ex.Not {
  6510. return !isNull, nil
  6511. }
  6512. return isNull, nil
  6513. case *parser.IsDistinctExpr:
  6514. left, err := e.evalExprWithAggregates(ex.Left, rows)
  6515. if err != nil {
  6516. return nil, err
  6517. }
  6518. right, err := e.evalExprWithAggregates(ex.Right, rows)
  6519. if err != nil {
  6520. return nil, err
  6521. }
  6522. distinct := false
  6523. switch {
  6524. case left == nil && right == nil:
  6525. distinct = false
  6526. case left == nil || right == nil:
  6527. distinct = true
  6528. default:
  6529. distinct = compare(left, right) != 0
  6530. }
  6531. if ex.Not {
  6532. return !distinct, nil
  6533. }
  6534. return distinct, nil
  6535. case *parser.BetweenExpr:
  6536. val, err := e.evalExprWithAggregates(ex.Left, rows)
  6537. if err != nil {
  6538. return nil, err
  6539. }
  6540. low, err := e.evalExprWithAggregates(ex.Low, rows)
  6541. if err != nil {
  6542. return nil, err
  6543. }
  6544. high, err := e.evalExprWithAggregates(ex.High, rows)
  6545. if err != nil {
  6546. return nil, err
  6547. }
  6548. if ex.Not {
  6549. // NOT BETWEEN: val < low OR val > high
  6550. var lessThan, greaterThan interface{}
  6551. if val == nil || low == nil {
  6552. lessThan = nil
  6553. } else {
  6554. lessThan = compare(val, low) < 0
  6555. }
  6556. if val == nil || high == nil {
  6557. greaterThan = nil
  6558. } else {
  6559. greaterThan = compare(val, high) > 0
  6560. }
  6561. // Three-valued OR
  6562. if toBool(lessThan) || toBool(greaterThan) {
  6563. return true, nil
  6564. }
  6565. if lessThan == nil || greaterThan == nil {
  6566. return nil, nil
  6567. }
  6568. return false, nil
  6569. } else {
  6570. // BETWEEN: val >= low AND val <= high
  6571. if val == nil {
  6572. return nil, nil
  6573. }
  6574. if low == nil {
  6575. if high != nil && compare(val, high) > 0 {
  6576. return false, nil
  6577. }
  6578. return nil, nil
  6579. }
  6580. if compare(val, low) < 0 {
  6581. return false, nil
  6582. }
  6583. if high == nil {
  6584. return nil, nil
  6585. }
  6586. return compare(val, high) <= 0, nil
  6587. }
  6588. case *parser.ArrayExpr:
  6589. elements := make([]*string, len(ex.Elements))
  6590. for i, element := range ex.Elements {
  6591. value, err := e.evalExprWithAggregates(element, rows)
  6592. if err != nil {
  6593. return nil, err
  6594. }
  6595. text, err := arrayValueElement(value)
  6596. if err != nil {
  6597. return nil, fmt.Errorf("ARRAY element %d: %w", i+1, err)
  6598. }
  6599. elements[i] = text
  6600. }
  6601. return formatArrayLiteral(elements), nil
  6602. case *parser.SubscriptExpr:
  6603. value, err := e.arrayOperand(ex.Expr, func() (interface{}, error) {
  6604. return e.evalExprWithAggregates(ex.Expr, rows)
  6605. })
  6606. if err != nil {
  6607. return nil, err
  6608. }
  6609. index, err := e.evalExprWithAggregates(ex.Index, rows)
  6610. if err != nil {
  6611. return nil, err
  6612. }
  6613. return e.subscriptArrayValue(ex.Expr, value, index)
  6614. case *parser.AnyAllExpr:
  6615. left, err := e.evalExprWithAggregates(ex.Left, rows)
  6616. if err != nil {
  6617. return nil, err
  6618. }
  6619. arrayValue, err := e.arrayOperand(ex.Array, func() (interface{}, error) {
  6620. return e.evalExprWithAggregates(ex.Array, rows)
  6621. })
  6622. if err != nil {
  6623. return nil, err
  6624. }
  6625. if arrayValue == nil {
  6626. return nil, nil
  6627. }
  6628. elements, err := e.parsedArray(ex.Array, arrayValue)
  6629. if err != nil {
  6630. return nil, fmt.Errorf("ANY/ALL requires an array operand: %w", err)
  6631. }
  6632. return evalQuantifiedComparison(ex.Op, ex.All, left, elements)
  6633. case *parser.InExpr:
  6634. left, err := e.evalExprWithAggregates(ex.Left, rows)
  6635. if err != nil {
  6636. return nil, err
  6637. }
  6638. // Handle subquery
  6639. if ex.Subquery != nil {
  6640. var result *Result
  6641. var err error
  6642. if e.subqueryCache != nil && e.outerRow == nil {
  6643. if cached, ok := e.subqueryCache[ex.Subquery]; ok {
  6644. result = cached
  6645. } else {
  6646. result, err = e.executeSelect(ex.Subquery)
  6647. if err == nil {
  6648. e.subqueryCache[ex.Subquery] = result
  6649. }
  6650. }
  6651. } else {
  6652. result, err = e.executeSelect(ex.Subquery)
  6653. }
  6654. if err != nil {
  6655. return nil, fmt.Errorf("IN subquery error: %w", err)
  6656. }
  6657. if len(result.Columns) != 1 {
  6658. return nil, fmt.Errorf("subquery in IN must return exactly one column")
  6659. }
  6660. if left == nil {
  6661. return nil, nil
  6662. }
  6663. sawNull := false
  6664. for _, resultRow := range result.Rows {
  6665. if len(resultRow) == 0 {
  6666. continue
  6667. }
  6668. v := resultRow[0]
  6669. if v == nil {
  6670. sawNull = true
  6671. continue
  6672. }
  6673. v, canonErr := e.canonicalArrayValue(ex.Left, v)
  6674. if canonErr != nil {
  6675. return nil, canonErr
  6676. }
  6677. if compare(left, v) == 0 {
  6678. if ex.Not {
  6679. return false, nil
  6680. }
  6681. return true, nil
  6682. }
  6683. }
  6684. if sawNull {
  6685. return nil, nil
  6686. }
  6687. if ex.Not {
  6688. return true, nil
  6689. }
  6690. return false, nil
  6691. }
  6692. // Handle value list
  6693. if len(ex.Values) == 0 {
  6694. return ex.Not, nil
  6695. }
  6696. if left == nil {
  6697. return nil, nil
  6698. }
  6699. sawNull := false
  6700. for _, val := range ex.Values {
  6701. v, err := e.evalExprWithAggregates(val, rows)
  6702. if err != nil {
  6703. return nil, err
  6704. }
  6705. if v == nil {
  6706. sawNull = true
  6707. continue
  6708. }
  6709. v, err = e.canonicalArrayValue(ex.Left, v)
  6710. if err != nil {
  6711. return nil, err
  6712. }
  6713. if compare(left, v) == 0 {
  6714. if ex.Not {
  6715. return false, nil
  6716. }
  6717. return true, nil
  6718. }
  6719. }
  6720. if sawNull {
  6721. return nil, nil
  6722. }
  6723. if ex.Not {
  6724. return true, nil
  6725. }
  6726. return false, nil
  6727. default:
  6728. // Literals and non-aggregate expressions.
  6729. if len(rows) > 0 {
  6730. return e.evalExpr(expr, rows[0])
  6731. }
  6732. return e.evalExpr(expr, storage.Row{})
  6733. }
  6734. }
  6735. // Helper functions
  6736. func (e *Executor) getSelectColumns(stmt *parser.SelectStmt, schema *storage.Schema) []string {
  6737. var columns []string
  6738. for _, col := range stmt.Columns {
  6739. if col.Star {
  6740. for _, c := range schema.Columns {
  6741. columns = append(columns, c.Name)
  6742. }
  6743. } else if col.Alias != "" {
  6744. columns = append(columns, col.Alias)
  6745. } else if ref, ok := col.Expr.(*parser.ColumnRef); ok {
  6746. columns = append(columns, ref.Column)
  6747. } else {
  6748. columns = append(columns, fmt.Sprintf("column%d", len(columns)+1))
  6749. }
  6750. }
  6751. return columns
  6752. }
  6753. func (e *Executor) hasAggregates(columns []parser.SelectColumn) bool {
  6754. for _, col := range columns {
  6755. if e.isAggregate(col.Expr) {
  6756. return true
  6757. }
  6758. }
  6759. return false
  6760. }
  6761. func (e *Executor) isAggregate(expr parser.Expr) bool {
  6762. if _, ok := expr.(*parser.WindowExpr); ok {
  6763. // Window functions are computed after grouping; they are not aggregates.
  6764. return false
  6765. }
  6766. if fn, ok := expr.(*parser.FunctionCall); ok {
  6767. name := strings.ToUpper(fn.Name)
  6768. if isAggregateCallName(name) {
  6769. return true
  6770. }
  6771. // Non-aggregate function: check if any arg contains an aggregate.
  6772. for _, arg := range fn.Args {
  6773. if e.isAggregate(arg) {
  6774. return true
  6775. }
  6776. }
  6777. return false
  6778. }
  6779. switch ex := expr.(type) {
  6780. case *parser.UnaryExpr:
  6781. return e.isAggregate(ex.Operand)
  6782. case *parser.BinaryExpr:
  6783. return e.isAggregate(ex.Left) || e.isAggregate(ex.Right)
  6784. case *parser.ParenExpr:
  6785. return e.isAggregate(ex.Expr)
  6786. case *parser.CaseExpr:
  6787. if ex.Operand != nil && e.isAggregate(ex.Operand) {
  6788. return true
  6789. }
  6790. for _, w := range ex.Whens {
  6791. if e.isAggregate(w.Condition) || e.isAggregate(w.Result) {
  6792. return true
  6793. }
  6794. }
  6795. if ex.Else != nil {
  6796. return e.isAggregate(ex.Else)
  6797. }
  6798. case *parser.CastExpr:
  6799. return e.isAggregate(ex.Expr)
  6800. case *parser.ArrayExpr:
  6801. for _, element := range ex.Elements {
  6802. if e.isAggregate(element) {
  6803. return true
  6804. }
  6805. }
  6806. return false
  6807. case *parser.SubscriptExpr:
  6808. return e.isAggregate(ex.Expr) || e.isAggregate(ex.Index)
  6809. case *parser.AnyAllExpr:
  6810. return e.isAggregate(ex.Left) || e.isAggregate(ex.Array)
  6811. case *parser.IsNullExpr:
  6812. return e.isAggregate(ex.Left)
  6813. case *parser.IsDistinctExpr:
  6814. return e.isAggregate(ex.Left) || e.isAggregate(ex.Right)
  6815. case *parser.BetweenExpr:
  6816. return e.isAggregate(ex.Left) || e.isAggregate(ex.Low) || e.isAggregate(ex.High)
  6817. case *parser.InExpr:
  6818. if e.isAggregate(ex.Left) {
  6819. return true
  6820. }
  6821. for _, val := range ex.Values {
  6822. if e.isAggregate(val) {
  6823. return true
  6824. }
  6825. }
  6826. return false
  6827. }
  6828. return false
  6829. }
  6830. // resolveGroupByAliases replaces GROUP BY references that name a SELECT alias
  6831. // with the aliased expression. SQLite allows `GROUP BY alias`, so grouping must
  6832. // use the same expression the projection evaluates.
  6833. func (e *Executor) resolveGroupByAliases(groupBy []parser.Expr, selectCols []parser.SelectColumn) []parser.Expr {
  6834. if len(groupBy) == 0 {
  6835. return groupBy
  6836. }
  6837. aliases := make(map[string]parser.Expr, len(selectCols))
  6838. for _, col := range selectCols {
  6839. if col.Alias != "" && col.Expr != nil {
  6840. aliases[strings.ToUpper(col.Alias)] = col.Expr
  6841. }
  6842. }
  6843. if len(aliases) == 0 {
  6844. return groupBy
  6845. }
  6846. out := make([]parser.Expr, len(groupBy))
  6847. for i, expr := range groupBy {
  6848. if ref, ok := expr.(*parser.ColumnRef); ok {
  6849. if target, ok := aliases[strings.ToUpper(ref.Column)]; ok {
  6850. out[i] = target
  6851. continue
  6852. }
  6853. }
  6854. out[i] = expr
  6855. }
  6856. return out
  6857. }
  6858. func (e *Executor) buildGroupKey(groupBy []parser.Expr, row storage.Row) string {
  6859. var parts []string
  6860. for _, expr := range groupBy {
  6861. val, _ := e.evalExpr(expr, row)
  6862. parts = append(parts, fmt.Sprintf("%v", val))
  6863. }
  6864. return strings.Join(parts, "|")
  6865. }
  6866. // resolveOrderByPositions replaces positional ORDER BY expressions (e.g. ORDER BY 1)
  6867. // with the corresponding SELECT column expressions per SQL-92 semantics.
  6868. func resolveOrderByPositions(orderBy []parser.OrderByItem, selectCols []parser.SelectColumn) []parser.OrderByItem {
  6869. result := make([]parser.OrderByItem, len(orderBy))
  6870. for i, item := range orderBy {
  6871. if lit, ok := item.Expr.(*parser.LiteralExpr); ok {
  6872. if pos, err := strconv.Atoi(lit.Value); err == nil && pos >= 1 && pos <= len(selectCols) {
  6873. col := selectCols[pos-1]
  6874. if col.Expr != nil {
  6875. result[i] = parser.OrderByItem{Expr: col.Expr, Desc: item.Desc, NullsOrder: item.NullsOrder}
  6876. continue
  6877. }
  6878. }
  6879. }
  6880. result[i] = item
  6881. }
  6882. return result
  6883. }
  6884. // orderByLess reports whether key slice a sorts before b under orderBy.
  6885. // Keys are precomputed per-row ORDER BY expression values, one per item.
  6886. func orderByLess(a, b []interface{}, orderBy []parser.OrderByItem) bool {
  6887. for i, item := range orderBy {
  6888. av, bv := a[i], b[i]
  6889. if av == nil || bv == nil {
  6890. if av == nil && bv == nil {
  6891. continue
  6892. }
  6893. // SQLite treats NULL as smaller than any value, so the default puts
  6894. // NULLs first for ASC and last for DESC. NULLS FIRST/LAST overrides it.
  6895. nullsFirst := !item.Desc
  6896. switch item.NullsOrder {
  6897. case parser.NullsFirst:
  6898. nullsFirst = true
  6899. case parser.NullsLast:
  6900. nullsFirst = false
  6901. }
  6902. if av == nil {
  6903. return nullsFirst
  6904. }
  6905. return !nullsFirst
  6906. }
  6907. cmp := compare(av, bv)
  6908. if cmp != 0 {
  6909. if item.Desc {
  6910. return cmp > 0
  6911. }
  6912. return cmp < 0
  6913. }
  6914. }
  6915. return false
  6916. }
  6917. // sortKeyOrder returns a permutation of [0..len(keys)) that sorts the keys
  6918. // ascending per orderBy.
  6919. func sortKeyOrder(keys [][]interface{}, orderBy []parser.OrderByItem) []int {
  6920. order := make([]int, len(keys))
  6921. for i := range order {
  6922. order[i] = i
  6923. }
  6924. sort.Slice(order, func(a, b int) bool {
  6925. return orderByLess(keys[order[a]], keys[order[b]], orderBy)
  6926. })
  6927. return order
  6928. }
  6929. // topNHeap is a bounded max-heap that keeps the k smallest elements (per
  6930. // orderByLess) seen so far.
  6931. type topNHeap struct {
  6932. keys [][]interface{}
  6933. idx []int
  6934. orderBy []parser.OrderByItem
  6935. }
  6936. func (h *topNHeap) Len() int { return len(h.idx) }
  6937. func (h *topNHeap) Less(i, j int) bool {
  6938. return orderByLess(h.keys[h.idx[j]], h.keys[h.idx[i]], h.orderBy)
  6939. }
  6940. func (h *topNHeap) Swap(i, j int) { h.idx[i], h.idx[j] = h.idx[j], h.idx[i] }
  6941. func (h *topNHeap) Push(x interface{}) { h.idx = append(h.idx, x.(int)) }
  6942. func (h *topNHeap) Pop() interface{} {
  6943. n := len(h.idx)
  6944. x := h.idx[n-1]
  6945. h.idx = h.idx[:n-1]
  6946. return x
  6947. }
  6948. // topNKeyOrder returns the indices of the k smallest keys (per orderByLess) in
  6949. // ascending order, without fully sorting all n elements. If k >= n it falls
  6950. // back to a full sort.
  6951. func topNKeyOrder(keys [][]interface{}, orderBy []parser.OrderByItem, k int) []int {
  6952. if k <= 0 {
  6953. return nil
  6954. }
  6955. if k >= len(keys) {
  6956. return sortKeyOrder(keys, orderBy)
  6957. }
  6958. h := &topNHeap{keys: keys, orderBy: orderBy, idx: make([]int, 0, k)}
  6959. for i := range keys {
  6960. if h.Len() < k {
  6961. heap.Push(h, i)
  6962. } else if orderByLess(keys[i], keys[h.idx[0]], orderBy) {
  6963. h.idx[0] = i
  6964. heap.Fix(h, 0)
  6965. }
  6966. }
  6967. selected := append([]int(nil), h.idx...)
  6968. sort.Slice(selected, func(a, b int) bool {
  6969. return orderByLess(keys[selected[a]], keys[selected[b]], orderBy)
  6970. })
  6971. return selected
  6972. }
  6973. func reorderRows(rows []storage.Row, order []int) {
  6974. tmp := make([]storage.Row, len(rows))
  6975. for i, idx := range order {
  6976. tmp[i] = rows[idx]
  6977. }
  6978. copy(rows, tmp)
  6979. }
  6980. // sortRowKeys precomputes the ORDER BY expression value for each row so each
  6981. // expression is evaluated once per row instead of O(n log n) times.
  6982. func (e *Executor) sortRowKeys(rows []storage.Row, orderBy []parser.OrderByItem) [][]interface{} {
  6983. keys := make([][]interface{}, len(rows))
  6984. for i, row := range rows {
  6985. ks := make([]interface{}, len(orderBy))
  6986. for j, item := range orderBy {
  6987. ks[j], _ = e.evalExpr(item.Expr, row)
  6988. }
  6989. keys[i] = ks
  6990. }
  6991. return keys
  6992. }
  6993. func (e *Executor) sortRows(rows []storage.Row, orderBy []parser.OrderByItem) {
  6994. order := sortKeyOrder(e.sortRowKeys(rows, orderBy), orderBy)
  6995. reorderRows(rows, order)
  6996. }
  6997. // topNRows sorts only enough to keep the k smallest rows (per orderBy).
  6998. func (e *Executor) topNRows(rows []storage.Row, orderBy []parser.OrderByItem, k int) []storage.Row {
  6999. order := topNKeyOrder(e.sortRowKeys(rows, orderBy), orderBy, k)
  7000. out := make([]storage.Row, len(order))
  7001. for i, idx := range order {
  7002. out[i] = rows[idx]
  7003. }
  7004. return out
  7005. }
  7006. // orderAndLimitRows applies ORDER BY (with a bounded top-N selection when a
  7007. // LIMIT is present), then OFFSET and LIMIT, preserving SQL semantics.
  7008. func (e *Executor) orderAndLimitRows(rows []storage.Row, orderBy []parser.OrderByItem, limitExpr, offsetExpr parser.Expr, selectCols []parser.SelectColumn) []storage.Row {
  7009. orderBy = resolveOrderByPositions(orderBy, selectCols)
  7010. var offset, limit int
  7011. hasOffset := offsetExpr != nil
  7012. hasLimit := limitExpr != nil
  7013. if hasOffset {
  7014. offset = e.evalIntExpr(offsetExpr)
  7015. }
  7016. if hasLimit {
  7017. limit = e.evalIntExpr(limitExpr)
  7018. }
  7019. if len(orderBy) > 0 {
  7020. if hasLimit && limit >= 0 {
  7021. k := offset + limit
  7022. if k >= 0 && k < len(rows) {
  7023. rows = e.topNRows(rows, orderBy, k)
  7024. } else {
  7025. e.sortRows(rows, orderBy)
  7026. }
  7027. } else {
  7028. e.sortRows(rows, orderBy)
  7029. }
  7030. }
  7031. if hasOffset {
  7032. if offset < len(rows) {
  7033. rows = rows[offset:]
  7034. } else {
  7035. rows = nil
  7036. }
  7037. }
  7038. if hasLimit {
  7039. if limit < len(rows) {
  7040. rows = rows[:limit]
  7041. }
  7042. }
  7043. return rows
  7044. }
  7045. // resultRowKey evaluates a single ORDER BY item against a result row, honoring
  7046. // select-column aliases exactly like the previous sortResultRows implementation.
  7047. func (e *Executor) resultRowKey(result *Result, rowIdx int, item parser.OrderByItem, columnNames []string) interface{} {
  7048. if ref, ok := item.Expr.(*parser.ColumnRef); ok && ref.Table == "" {
  7049. for idx, name := range columnNames {
  7050. if strings.EqualFold(name, ref.Column) {
  7051. if idx < len(result.Rows[rowIdx]) {
  7052. return result.Rows[rowIdx][idx]
  7053. }
  7054. }
  7055. }
  7056. }
  7057. row := e.resultRowToStorageRow(result, rowIdx)
  7058. v, _ := e.evalExpr(item.Expr, row)
  7059. return v
  7060. }
  7061. // resultRowKeys precomputes the ORDER BY expression value for each result row.
  7062. func (e *Executor) resultRowKeys(result *Result, orderBy []parser.OrderByItem, columnNames []string) [][]interface{} {
  7063. keys := make([][]interface{}, len(result.Rows))
  7064. for i := range result.Rows {
  7065. ks := make([]interface{}, len(orderBy))
  7066. for j, item := range orderBy {
  7067. ks[j] = e.resultRowKey(result, i, item, columnNames)
  7068. }
  7069. keys[i] = ks
  7070. }
  7071. return keys
  7072. }
  7073. // sortResultRows sorts Result.Rows based on ORDER BY clauses.
  7074. // It handles column aliases by matching them against the select columns.
  7075. func (e *Executor) sortResultRows(result *Result, orderBy []parser.OrderByItem, selectColumns []parser.SelectColumn, columnNames []string) {
  7076. orderBy = resolveOrderByPositions(orderBy, selectColumns)
  7077. order := sortKeyOrder(e.resultRowKeys(result, orderBy, columnNames), orderBy)
  7078. rows := make([][]interface{}, len(order))
  7079. for i, idx := range order {
  7080. rows[i] = result.Rows[idx]
  7081. }
  7082. result.Rows = rows
  7083. }
  7084. // orderAndLimitResultRows applies ORDER BY (with bounded top-N selection when a
  7085. // LIMIT is present), then OFFSET and LIMIT, to a Result's rows.
  7086. func (e *Executor) orderAndLimitResultRows(result *Result, orderBy []parser.OrderByItem, limitExpr, offsetExpr parser.Expr, selectCols []parser.SelectColumn, columnNames []string) {
  7087. orderBy = resolveOrderByPositions(orderBy, selectCols)
  7088. var offset, limit int
  7089. hasOffset := offsetExpr != nil
  7090. hasLimit := limitExpr != nil
  7091. if hasOffset {
  7092. offset = e.evalIntExpr(offsetExpr)
  7093. }
  7094. if hasLimit {
  7095. limit = e.evalIntExpr(limitExpr)
  7096. }
  7097. if len(orderBy) > 0 {
  7098. if hasLimit && limit >= 0 {
  7099. k := offset + limit
  7100. if k >= 0 && k < len(result.Rows) {
  7101. order := topNKeyOrder(e.resultRowKeys(result, orderBy, columnNames), orderBy, k)
  7102. rows := make([][]interface{}, len(order))
  7103. for i, idx := range order {
  7104. rows[i] = result.Rows[idx]
  7105. }
  7106. result.Rows = rows
  7107. } else {
  7108. e.sortResultRows(result, orderBy, nil, columnNames)
  7109. }
  7110. } else {
  7111. e.sortResultRows(result, orderBy, nil, columnNames)
  7112. }
  7113. }
  7114. if hasOffset {
  7115. if offset < len(result.Rows) {
  7116. result.Rows = result.Rows[offset:]
  7117. } else {
  7118. result.Rows = nil
  7119. }
  7120. result.RowCount = len(result.Rows)
  7121. }
  7122. if hasLimit {
  7123. if limit < len(result.Rows) {
  7124. result.Rows = result.Rows[:limit]
  7125. }
  7126. result.RowCount = len(result.Rows)
  7127. }
  7128. }
  7129. // resultRowToStorageRow converts a Result row back to storage.Row for expression evaluation.
  7130. func (e *Executor) resultRowToStorageRow(result *Result, rowIdx int) storage.Row {
  7131. row := make(storage.Row)
  7132. for colIdx, colName := range result.Columns {
  7133. if colIdx < len(result.Rows[rowIdx]) {
  7134. row[colName] = result.Rows[rowIdx][colIdx]
  7135. }
  7136. }
  7137. return row
  7138. }
  7139. func (e *Executor) evalIntExpr(expr parser.Expr) int {
  7140. val, _ := e.evalExpr(expr, nil)
  7141. return int(toFloat(val))
  7142. }
  7143. // Type conversion helpers
  7144. func isIntVal(v interface{}) bool {
  7145. switch v.(type) {
  7146. case int64, int, bool:
  7147. return true
  7148. default:
  7149. return false
  7150. }
  7151. }
  7152. func toInt64(v interface{}) int64 {
  7153. switch val := v.(type) {
  7154. case int64:
  7155. return val
  7156. case int:
  7157. return int64(val)
  7158. case float64:
  7159. return int64(val)
  7160. case bool:
  7161. if val {
  7162. return 1
  7163. }
  7164. return 0
  7165. case jsonText:
  7166. // -> returns JSON text, so integer conversion parses its text form.
  7167. // Keep exact integers exact before falling back to float truncation.
  7168. if i, err := strconv.ParseInt(string(val), 10, 64); err == nil {
  7169. return i
  7170. }
  7171. f, _ := strconv.ParseFloat(string(val), 64)
  7172. return int64(f)
  7173. default:
  7174. return 0
  7175. }
  7176. }
  7177. func toFloat(v interface{}) float64 {
  7178. switch val := v.(type) {
  7179. case nil:
  7180. return 0
  7181. case int64:
  7182. return float64(val)
  7183. case int:
  7184. return float64(val)
  7185. case float64:
  7186. return val
  7187. case bool:
  7188. if val {
  7189. return 1
  7190. }
  7191. return 0
  7192. case string:
  7193. f, _ := strconv.ParseFloat(val, 64)
  7194. return f
  7195. case jsonText:
  7196. f, _ := strconv.ParseFloat(string(val), 64)
  7197. return f
  7198. default:
  7199. return 0
  7200. }
  7201. }
  7202. func toBool(v interface{}) bool {
  7203. switch val := v.(type) {
  7204. case nil:
  7205. return false
  7206. case bool:
  7207. return val
  7208. case int64:
  7209. return val != 0
  7210. case int:
  7211. return val != 0
  7212. case float64:
  7213. return val != 0
  7214. case string:
  7215. return val != "" && val != "0" && strings.ToLower(val) != "false"
  7216. case jsonText:
  7217. s := string(val)
  7218. return s != "" && s != "0" && strings.ToLower(s) != "false"
  7219. default:
  7220. return false
  7221. }
  7222. }
  7223. func toString(v interface{}) string {
  7224. if v == nil {
  7225. return ""
  7226. }
  7227. switch t := v.(type) {
  7228. case string:
  7229. return t
  7230. case []byte:
  7231. return string(t)
  7232. case jsonText:
  7233. return string(t)
  7234. case bool:
  7235. if t {
  7236. return "1"
  7237. }
  7238. return "0"
  7239. case int:
  7240. return strconv.FormatInt(int64(t), 10)
  7241. case int64:
  7242. return strconv.FormatInt(t, 10)
  7243. case uint:
  7244. return strconv.FormatUint(uint64(t), 10)
  7245. case uint64:
  7246. return strconv.FormatUint(t, 10)
  7247. case float32:
  7248. return formatSQLiteReal(float64(t))
  7249. case float64:
  7250. return formatSQLiteReal(t)
  7251. default:
  7252. return fmt.Sprintf("%v", v)
  7253. }
  7254. }
  7255. func compare(a, b interface{}) int {
  7256. if a == nil && b == nil {
  7257. return 0
  7258. }
  7259. if a == nil {
  7260. return -1
  7261. }
  7262. if b == nil {
  7263. return 1
  7264. }
  7265. // Try numeric comparison
  7266. fa, oka := toNumeric(a)
  7267. fb, okb := toNumeric(b)
  7268. if oka && okb {
  7269. if fa < fb {
  7270. return -1
  7271. }
  7272. if fa > fb {
  7273. return 1
  7274. }
  7275. return 0
  7276. }
  7277. // String comparison
  7278. sa := toString(a)
  7279. sb := toString(b)
  7280. return strings.Compare(sa, sb)
  7281. }
  7282. func toNumeric(v interface{}) (float64, bool) {
  7283. switch val := v.(type) {
  7284. case int64:
  7285. return float64(val), true
  7286. case int:
  7287. return float64(val), true
  7288. case float64:
  7289. return val, true
  7290. case string:
  7291. f, err := strconv.ParseFloat(val, 64)
  7292. return f, err == nil
  7293. case jsonText:
  7294. f, err := strconv.ParseFloat(string(val), 64)
  7295. return f, err == nil
  7296. default:
  7297. return 0, false
  7298. }
  7299. }
  7300. // splitANDClauses flattens a tree of AND binary expressions into a slice of leaf conditions.
  7301. func splitANDClauses(expr parser.Expr) []parser.Expr {
  7302. if bin, ok := expr.(*parser.BinaryExpr); ok && bin.Op == lexer.TokenAND {
  7303. left := splitANDClauses(bin.Left)
  7304. right := splitANDClauses(bin.Right)
  7305. return append(left, right...)
  7306. }
  7307. return []parser.Expr{expr}
  7308. }
  7309. // collectColumnRefs returns all unqualified column names referenced in an expression.
  7310. func collectColumnRefs(expr parser.Expr) []string {
  7311. var refs []string
  7312. var hasSubquery bool
  7313. var walk func(parser.Expr)
  7314. walk = func(e parser.Expr) {
  7315. if e == nil {
  7316. return
  7317. }
  7318. switch n := e.(type) {
  7319. case *parser.ColumnRef:
  7320. refs = append(refs, n.Column)
  7321. case *parser.BinaryExpr:
  7322. walk(n.Left)
  7323. walk(n.Right)
  7324. case *parser.UnaryExpr:
  7325. walk(n.Operand)
  7326. case *parser.InExpr:
  7327. walk(n.Left)
  7328. // Check for subquery
  7329. if n.Subquery != nil {
  7330. hasSubquery = true
  7331. }
  7332. for _, v := range n.Values {
  7333. walk(v)
  7334. }
  7335. case *parser.BetweenExpr:
  7336. walk(n.Left)
  7337. walk(n.Low)
  7338. walk(n.High)
  7339. case *parser.LikeExpr:
  7340. walk(n.Left)
  7341. walk(n.Pattern)
  7342. case *parser.IsNullExpr:
  7343. walk(n.Left)
  7344. case *parser.IsDistinctExpr:
  7345. walk(n.Left)
  7346. walk(n.Right)
  7347. case *parser.CaseExpr:
  7348. walk(n.Operand)
  7349. for _, w := range n.Whens {
  7350. walk(w.Condition)
  7351. walk(w.Result)
  7352. }
  7353. walk(n.Else)
  7354. case *parser.FunctionCall:
  7355. for _, a := range n.Args {
  7356. walk(a)
  7357. }
  7358. case *parser.ParenExpr:
  7359. walk(n.Expr)
  7360. case *parser.CastExpr:
  7361. walk(n.Expr)
  7362. case *parser.ArrayExpr:
  7363. for _, element := range n.Elements {
  7364. walk(element)
  7365. }
  7366. case *parser.SubscriptExpr:
  7367. walk(n.Expr)
  7368. walk(n.Index)
  7369. case *parser.AnyAllExpr:
  7370. walk(n.Left)
  7371. walk(n.Array)
  7372. case *parser.SubqueryExpr:
  7373. // Subqueries may reference outer columns
  7374. hasSubquery = true
  7375. case *parser.ExistsExpr:
  7376. // EXISTS subqueries may reference outer columns
  7377. hasSubquery = true
  7378. case *parser.LiteralExpr:
  7379. // Literals have no column refs
  7380. }
  7381. }
  7382. walk(expr)
  7383. // If we have subqueries, add a sentinel value to indicate non-constant
  7384. if hasSubquery {
  7385. refs = append(refs, "__subquery__")
  7386. }
  7387. return refs
  7388. }
  7389. type tableColRef struct{ tbl, col string }
  7390. // collectTableColumnRefs returns all column references with their table qualifier (may be "").
  7391. func collectTableColumnRefs(expr parser.Expr) []tableColRef {
  7392. var refs []tableColRef
  7393. var walk func(parser.Expr)
  7394. walk = func(e parser.Expr) {
  7395. if e == nil {
  7396. return
  7397. }
  7398. switch n := e.(type) {
  7399. case *parser.ColumnRef:
  7400. refs = append(refs, tableColRef{tbl: n.Table, col: n.Column})
  7401. case *parser.BinaryExpr:
  7402. walk(n.Left)
  7403. walk(n.Right)
  7404. case *parser.UnaryExpr:
  7405. walk(n.Operand)
  7406. case *parser.InExpr:
  7407. walk(n.Left)
  7408. for _, v := range n.Values {
  7409. walk(v)
  7410. }
  7411. case *parser.BetweenExpr:
  7412. walk(n.Left)
  7413. walk(n.Low)
  7414. walk(n.High)
  7415. case *parser.LikeExpr:
  7416. walk(n.Left)
  7417. walk(n.Pattern)
  7418. case *parser.IsNullExpr:
  7419. walk(n.Left)
  7420. case *parser.IsDistinctExpr:
  7421. walk(n.Left)
  7422. walk(n.Right)
  7423. case *parser.CaseExpr:
  7424. walk(n.Operand)
  7425. for _, w := range n.Whens {
  7426. walk(w.Condition)
  7427. walk(w.Result)
  7428. }
  7429. walk(n.Else)
  7430. case *parser.FunctionCall:
  7431. for _, a := range n.Args {
  7432. walk(a)
  7433. }
  7434. case *parser.ParenExpr:
  7435. walk(n.Expr)
  7436. case *parser.CastExpr:
  7437. walk(n.Expr)
  7438. case *parser.ArrayExpr:
  7439. for _, element := range n.Elements {
  7440. walk(element)
  7441. }
  7442. case *parser.SubscriptExpr:
  7443. walk(n.Expr)
  7444. walk(n.Index)
  7445. case *parser.AnyAllExpr:
  7446. walk(n.Left)
  7447. walk(n.Array)
  7448. }
  7449. }
  7450. walk(expr)
  7451. return refs
  7452. }
  7453. // combineAND combines a list of expressions with AND.
  7454. func combineAND(clauses []parser.Expr) parser.Expr {
  7455. if len(clauses) == 0 {
  7456. return nil
  7457. }
  7458. result := clauses[0]
  7459. for _, c := range clauses[1:] {
  7460. result = &parser.BinaryExpr{Left: result, Op: lexer.TokenAND, Right: c}
  7461. }
  7462. return result
  7463. }
  7464. // matchLike matches a string against a SQL LIKE pattern.
  7465. func matchLike(s, pattern string) bool {
  7466. // Simple implementation - convert to lowercase for case-insensitive matching
  7467. s = strings.ToLower(s)
  7468. pattern = strings.ToLower(pattern)
  7469. return matchLikeHelper(s, pattern)
  7470. }
  7471. func matchLikeHelper(s, p string) bool {
  7472. if p == "" {
  7473. return s == ""
  7474. }
  7475. if p[0] == '%' {
  7476. // % matches any sequence
  7477. for i := 0; i <= len(s); i++ {
  7478. if matchLikeHelper(s[i:], p[1:]) {
  7479. return true
  7480. }
  7481. }
  7482. return false
  7483. }
  7484. if s == "" {
  7485. return false
  7486. }
  7487. if p[0] == '_' || p[0] == s[0] {
  7488. return matchLikeHelper(s[1:], p[1:])
  7489. }
  7490. return false
  7491. }
  7492. // matchGlob matches a string against a GLOB pattern.
  7493. // GLOB uses * for any sequence and ? for single character (case-sensitive).
  7494. func matchGlob(pattern, s string) bool {
  7495. return matchGlobHelper(pattern, s)
  7496. }
  7497. func matchGlobHelper(p, s string) bool {
  7498. if p == "" {
  7499. return s == ""
  7500. }
  7501. if p[0] == '*' {
  7502. // * matches any sequence
  7503. for i := 0; i <= len(s); i++ {
  7504. if matchGlobHelper(p[1:], s[i:]) {
  7505. return true
  7506. }
  7507. }
  7508. return false
  7509. }
  7510. if s == "" {
  7511. return false
  7512. }
  7513. if p[0] == '?' || p[0] == s[0] {
  7514. return matchGlobHelper(p[1:], s[1:])
  7515. }
  7516. // Handle character classes [...]
  7517. if p[0] == '[' {
  7518. end := strings.Index(p, "]")
  7519. if end > 0 {
  7520. class := p[1:end]
  7521. match := false
  7522. negate := false
  7523. if len(class) > 0 && class[0] == '^' {
  7524. negate = true
  7525. class = class[1:]
  7526. }
  7527. for _, c := range class {
  7528. if byte(c) == s[0] {
  7529. match = true
  7530. break
  7531. }
  7532. }
  7533. if negate {
  7534. match = !match
  7535. }
  7536. if match {
  7537. return matchGlobHelper(p[end+1:], s[1:])
  7538. }
  7539. }
  7540. }
  7541. return false
  7542. }
  7543. // applyDistinct removes duplicate rows from the result
  7544. func (e *Executor) applyDistinct(rows [][]interface{}) [][]interface{} {
  7545. if len(rows) == 0 {
  7546. return rows
  7547. }
  7548. seen := make(map[string]bool)
  7549. uniqueRows := make([][]interface{}, 0)
  7550. for _, row := range rows {
  7551. // Create a key from all column values
  7552. key := ""
  7553. for i, val := range row {
  7554. if i > 0 {
  7555. key += "\x00" // Use null byte as separator
  7556. }
  7557. key += fmt.Sprintf("%v", val)
  7558. }
  7559. if !seen[key] {
  7560. seen[key] = true
  7561. uniqueRows = append(uniqueRows, row)
  7562. }
  7563. }
  7564. return uniqueRows
  7565. }