2
0

executor.go 187 KB

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