executor.go 185 KB

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