executor.go 191 KB

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