2
0

executor.go 193 KB

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