executor.go 188 KB

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