executor.go 187 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148
  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, err := constantDefaultValue(e, col.Name, constraint.Default)
  3314. if err != nil {
  3315. return nil, err
  3316. }
  3317. col.Default = val
  3318. }
  3319. case parser.ConstraintAutoIncrement:
  3320. schema.AutoIncrement = true
  3321. }
  3322. }
  3323. schema.Columns = append(schema.Columns, col)
  3324. }
  3325. // Handle table-level constraints
  3326. for _, constraint := range stmt.Constraints {
  3327. if constraint.Type == parser.ConstraintPrimaryKey && len(constraint.Columns) > 0 {
  3328. schema.PrimaryKey = constraint.Columns[0]
  3329. for i := range schema.Columns {
  3330. if strings.EqualFold(schema.Columns[i].Name, schema.PrimaryKey) {
  3331. schema.Columns[i].PrimaryKey = true
  3332. schema.Columns[i].Nullable = false
  3333. }
  3334. }
  3335. }
  3336. }
  3337. // Translate inline/table UNIQUE constraints (Gogs/GORM style) into the same
  3338. // scan-validated unique Index metadata that explicit CREATE UNIQUE INDEX
  3339. // produces, so both enforcement and the catalog observe them.
  3340. uniqIndexes := e.uniqueConstraintIndexes(stmt)
  3341. // Column references in generated expressions must resolve against the new
  3342. // table, so validate them once every column is known.
  3343. for _, colDef := range stmt.Columns {
  3344. if colDef.GeneratedExpr == nil {
  3345. continue
  3346. }
  3347. if err := ValidateIndexColumns(colDef.GeneratedExpr, schema); err != nil {
  3348. return nil, err
  3349. }
  3350. }
  3351. if err := e.schema.CreateTable(schema); err != nil {
  3352. if stmt.IfNotExists && strings.Contains(err.Error(), "table already exists") {
  3353. return NewResult("CREATE TABLE"), nil
  3354. }
  3355. return nil, err
  3356. }
  3357. // Register each materialized unique index. On failure, best-effort cleanup of
  3358. // the table and any indexes already created for it (DDL is not transactional).
  3359. var created []*storage.Index
  3360. for _, idx := range uniqIndexes {
  3361. if err := e.schema.CreateIndex(idx); err != nil {
  3362. for _, c := range created {
  3363. e.schema.DropIndex(c.Name)
  3364. }
  3365. e.schema.DropTable(stmt.Table.Name)
  3366. return nil, err
  3367. }
  3368. created = append(created, idx)
  3369. }
  3370. if err := e.SyncCatalog(); err != nil {
  3371. return nil, err
  3372. }
  3373. result := NewResult("CREATE TABLE")
  3374. return result, nil
  3375. }
  3376. // uniqueConstraintIndexes translates a CREATE TABLE's inline/table UNIQUE
  3377. // constraints into unique Index definitions. Named constraints keep their name;
  3378. // unnamed constraints (column-level UNIQUE, or bare UNIQUE(col,...)) receive a
  3379. // deterministic internal name derived from the table and columns.
  3380. func (e *Executor) uniqueConstraintIndexes(stmt *parser.CreateTableStmt) []*storage.Index {
  3381. var indexes []*storage.Index
  3382. used := make(map[string]bool)
  3383. uniqueName := func(base string, columns []string) string {
  3384. if base == "" {
  3385. base = "uniq_" + strings.ToLower(stmt.Table.Name) + "_" + strings.ToLower(strings.Join(columns, "_"))
  3386. }
  3387. name := base
  3388. for n := 2; used[strings.ToLower(name)]; n++ {
  3389. name = fmt.Sprintf("%s_%d", base, n)
  3390. }
  3391. used[strings.ToLower(name)] = true
  3392. return name
  3393. }
  3394. add := func(name string, columns []string, conflict parser.ConflictAction, hasConflict bool) {
  3395. idx := &storage.Index{Name: uniqueName(name, columns), Table: stmt.Table.Name, Unique: true}
  3396. if hasConflict {
  3397. idx.OnConflict = conflictActionName(conflict)
  3398. }
  3399. for _, c := range columns {
  3400. idx.Columns = append(idx.Columns, storage.IndexColumn{Name: c})
  3401. }
  3402. indexes = append(indexes, idx)
  3403. }
  3404. for _, constraint := range stmt.Constraints {
  3405. if constraint.Type == parser.ConstraintUnique && len(constraint.Columns) > 0 {
  3406. add(constraint.Name, constraint.Columns, constraint.OnConflict, constraint.HasOnConflict)
  3407. }
  3408. }
  3409. for _, colDef := range stmt.Columns {
  3410. for _, constraint := range colDef.Constraints {
  3411. if constraint.Type == parser.ConstraintUnique {
  3412. add("", []string{colDef.Name}, constraint.OnConflict, constraint.HasOnConflict)
  3413. }
  3414. }
  3415. }
  3416. return indexes
  3417. }
  3418. // conflictActionName maps a parsed conflict action to the durable index metadata
  3419. // spelling (empty for the default ABORT).
  3420. func conflictActionName(action parser.ConflictAction) string {
  3421. switch action {
  3422. case parser.ConflictReplace:
  3423. return "REPLACE"
  3424. case parser.ConflictIgnore:
  3425. return "IGNORE"
  3426. case parser.ConflictFail:
  3427. return "FAIL"
  3428. case parser.ConflictRollback:
  3429. return "ROLLBACK"
  3430. default:
  3431. return "ABORT"
  3432. }
  3433. }
  3434. // executeDropTable executes a DROP TABLE statement.
  3435. func (e *Executor) executeDropTable(stmt *parser.DropTableStmt) (*Result, error) {
  3436. for _, tableRef := range stmt.Tables {
  3437. if !e.schema.TableExists(tableRef.Name) {
  3438. if stmt.IfExists {
  3439. continue
  3440. }
  3441. return nil, fmt.Errorf("table not found: %s", tableRef.Name)
  3442. }
  3443. // First, drop all indexes associated with this table
  3444. indexes, _ := e.schema.ListTableIndexes(tableRef.Name)
  3445. for _, idx := range indexes {
  3446. // Clear index entries
  3447. columns := make([]string, len(idx.Columns))
  3448. for i, col := range idx.Columns {
  3449. columns[i] = col.Name
  3450. }
  3451. e.session.ClearIndex(idx.Name, tableRef.Name, columns)
  3452. // Drop the index schema
  3453. e.schema.DropIndex(idx.Name)
  3454. }
  3455. // DropTable removes durable rows and schema state together.
  3456. if err := e.schema.DropTable(tableRef.Name); err != nil {
  3457. return nil, err
  3458. }
  3459. e.session.InvalidateCache(tableRef.Name)
  3460. }
  3461. if err := e.SyncCatalog(); err != nil {
  3462. return nil, err
  3463. }
  3464. result := NewResult("DROP TABLE")
  3465. return result, nil
  3466. }
  3467. // executeCreateIndex creates a new index.
  3468. func (e *Executor) executeCreateIndex(stmt *parser.CreateIndexStmt) (*Result, error) {
  3469. // Check if index already exists
  3470. if e.schema.IndexExists(stmt.Name) {
  3471. if stmt.IfNotExists {
  3472. result := NewResult("CREATE INDEX")
  3473. return result, nil
  3474. }
  3475. return nil, fmt.Errorf("index already exists: %s", stmt.Name)
  3476. }
  3477. // Verify table exists
  3478. if !e.schema.TableExists(stmt.Table) {
  3479. return nil, fmt.Errorf("table not found: %s", stmt.Table)
  3480. }
  3481. // Verify columns exist
  3482. schema, err := e.schema.GetSchema(stmt.Table)
  3483. if err != nil {
  3484. return nil, err
  3485. }
  3486. for _, col := range stmt.Columns {
  3487. if col.Expr != nil {
  3488. // Expression indexes are evaluated by the stateless evaluator; make
  3489. // sure the persisted text parses, is deterministic, and only
  3490. // references columns of the indexed table.
  3491. text := parser.FormatExpr(col.Expr)
  3492. if _, err := parseStoredExpr(text); err != nil {
  3493. return nil, err
  3494. }
  3495. if err := ValidateIndexColumns(col.Expr, schema); err != nil {
  3496. return nil, err
  3497. }
  3498. continue
  3499. }
  3500. if _, found := schema.GetColumn(col.Name); !found {
  3501. return nil, fmt.Errorf("column not found: %s", col.Name)
  3502. }
  3503. }
  3504. // Create storage index
  3505. index := &storage.Index{
  3506. Name: stmt.Name,
  3507. Table: stmt.Table,
  3508. Unique: stmt.Unique,
  3509. }
  3510. for _, col := range stmt.Columns {
  3511. ic := storage.IndexColumn{
  3512. Name: col.Name,
  3513. Desc: col.Desc,
  3514. }
  3515. if col.Expr != nil {
  3516. ic.Expression = parser.FormatExpr(col.Expr)
  3517. }
  3518. index.Columns = append(index.Columns, ic)
  3519. }
  3520. if stmt.Unique {
  3521. // Validate existing rows and register the index under the table's
  3522. // exclusive gate so no concurrent writer can insert a conflicting value
  3523. // between validation and registration.
  3524. if err := e.table.CreateUniqueIndex(index); err != nil {
  3525. if stmt.IfNotExists && strings.Contains(err.Error(), "index already exists") {
  3526. return NewResult("CREATE INDEX"), nil
  3527. }
  3528. return nil, err
  3529. }
  3530. } else {
  3531. if err := e.schema.CreateIndex(index); err != nil {
  3532. if stmt.IfNotExists && strings.Contains(err.Error(), "index already exists") {
  3533. return NewResult("CREATE INDEX"), nil
  3534. }
  3535. return nil, err
  3536. }
  3537. }
  3538. // Build index entries for existing rows
  3539. columns := make([]string, len(stmt.Columns))
  3540. for i, col := range stmt.Columns {
  3541. columns[i] = col.Name
  3542. }
  3543. if err := e.session.BuildIndex(stmt.Name, stmt.Table, columns); err != nil {
  3544. // Rollback index creation on failure
  3545. e.schema.DropIndex(stmt.Name)
  3546. return nil, fmt.Errorf("failed to build index: %w", err)
  3547. }
  3548. result := NewResult("CREATE INDEX")
  3549. return result, nil
  3550. }
  3551. // executeDropIndex drops an index.
  3552. func (e *Executor) executeDropIndex(stmt *parser.DropIndexStmt) (*Result, error) {
  3553. if !e.schema.IndexExists(stmt.Name) {
  3554. if stmt.IfExists {
  3555. result := NewResult("DROP INDEX")
  3556. return result, nil
  3557. }
  3558. return nil, fmt.Errorf("index not found: %s", stmt.Name)
  3559. }
  3560. // Get index info to clear entries
  3561. index, err := e.schema.GetIndex(stmt.Name)
  3562. if err == nil && index != nil {
  3563. columns := make([]string, len(index.Columns))
  3564. for i, col := range index.Columns {
  3565. columns[i] = col.Name
  3566. }
  3567. e.session.ClearIndex(stmt.Name, index.Table, columns)
  3568. }
  3569. if err := e.schema.DropIndex(stmt.Name); err != nil {
  3570. return nil, err
  3571. }
  3572. result := NewResult("DROP INDEX")
  3573. return result, nil
  3574. }
  3575. func (e *Executor) executeCreateView(stmt *parser.CreateViewStmt) (*Result, error) {
  3576. name := strings.ToLower(stmt.View.Name)
  3577. if _, exists := e.views[name]; exists {
  3578. if stmt.IfNotExists {
  3579. return NewResult("CREATE VIEW"), nil
  3580. }
  3581. return nil, fmt.Errorf("view already exists: %s", stmt.View.Name)
  3582. }
  3583. e.views[name] = stmt.Select
  3584. // Derive view columns from SELECT list for catalog registration.
  3585. var viewCols []analyzer.ColumnInfo
  3586. hasStar := false
  3587. for _, col := range stmt.Select.Columns {
  3588. if col.Star {
  3589. hasStar = true
  3590. break
  3591. }
  3592. colName := col.Alias
  3593. if colName == "" {
  3594. if ref, ok := col.Expr.(*parser.ColumnRef); ok {
  3595. colName = ref.Column
  3596. } else {
  3597. colName = fmt.Sprintf("col_%d", len(viewCols))
  3598. }
  3599. }
  3600. viewCols = append(viewCols, analyzer.ColumnInfo{
  3601. Name: colName,
  3602. TableName: stmt.View.Name,
  3603. Type: analyzer.TypeAny,
  3604. Nullable: true,
  3605. })
  3606. }
  3607. // For SELECT *, pull columns from the underlying table(s).
  3608. if hasStar && len(stmt.Select.From) > 0 {
  3609. baseName := stmt.Select.From[0].Name
  3610. if schema, err := e.schema.GetSchema(baseName); err == nil {
  3611. for _, c := range schema.Columns {
  3612. viewCols = append(viewCols, analyzer.ColumnInfo{
  3613. Name: c.Name,
  3614. TableName: stmt.View.Name,
  3615. Type: analyzer.TypeAny,
  3616. Nullable: true,
  3617. })
  3618. }
  3619. }
  3620. }
  3621. // Register in catalog so the analyzer accepts SELECT FROM this view.
  3622. e.catalog.CreateTable(&analyzer.TableInfo{ //nolint:errcheck
  3623. Name: stmt.View.Name,
  3624. Columns: viewCols,
  3625. IsView: true,
  3626. })
  3627. return NewResult("CREATE VIEW"), nil
  3628. }
  3629. func (e *Executor) executeDropView(stmt *parser.DropViewStmt) (*Result, error) {
  3630. for _, ref := range stmt.Views {
  3631. name := strings.ToLower(ref.Name)
  3632. if _, exists := e.views[name]; !exists {
  3633. if stmt.IfExists {
  3634. continue
  3635. }
  3636. return nil, fmt.Errorf("view not found: %s", ref.Name)
  3637. }
  3638. delete(e.views, name)
  3639. e.catalog.DropTable(ref.Name) //nolint:errcheck
  3640. }
  3641. return NewResult("DROP VIEW"), nil
  3642. }
  3643. // executeAlterTable executes an ALTER TABLE statement.
  3644. func (e *Executor) executeAlterTable(stmt *parser.AlterTableStmt) (*Result, error) {
  3645. switch action := stmt.Action.(type) {
  3646. case *parser.AddColumnAction:
  3647. return e.executeAlterTableAddColumn(stmt.Table, action)
  3648. case *parser.DropColumnAction:
  3649. return e.executeAlterTableDropColumn(stmt.Table, action)
  3650. case *parser.RenameTableAction:
  3651. return e.executeAlterTableRename(stmt.Table, action)
  3652. case *parser.RenameColumnAction:
  3653. return e.executeAlterTableRenameColumn(stmt.Table, action)
  3654. default:
  3655. return nil, fmt.Errorf("unsupported ALTER TABLE action: %T", action)
  3656. }
  3657. }
  3658. // executeAlterTableAddColumn adds a column to a table.
  3659. func (e *Executor) executeAlterTableAddColumn(table string, action *parser.AddColumnAction) (*Result, error) {
  3660. if action.IfNotExists {
  3661. schema, err := e.schema.GetSchema(table)
  3662. if err != nil {
  3663. return nil, err
  3664. }
  3665. if _, exists := schema.GetColumn(action.Column.Name); exists {
  3666. return NewResult("ALTER TABLE"), nil
  3667. }
  3668. }
  3669. col := storage.Column{
  3670. Name: action.Column.Name,
  3671. Type: action.Column.Type.Name,
  3672. Nullable: true,
  3673. }
  3674. // Process column constraints
  3675. for _, constraint := range action.Column.Constraints {
  3676. switch constraint.Type {
  3677. case parser.ConstraintPrimaryKey:
  3678. col.PrimaryKey = true
  3679. col.Nullable = false
  3680. case parser.ConstraintNotNull:
  3681. col.Nullable = false
  3682. case parser.ConstraintDefault:
  3683. if constraint.Default != nil {
  3684. val, err := constantDefaultValue(e, col.Name, constraint.Default)
  3685. if err != nil {
  3686. return nil, err
  3687. }
  3688. col.Default = val
  3689. }
  3690. }
  3691. }
  3692. if err := e.schema.AddColumn(table, col); err != nil {
  3693. if action.IfNotExists && strings.Contains(err.Error(), "column already exists") {
  3694. return NewResult("ALTER TABLE"), nil
  3695. }
  3696. return nil, err
  3697. }
  3698. // Update catalog
  3699. e.SyncCatalog()
  3700. result := NewResult("ALTER TABLE")
  3701. return result, nil
  3702. }
  3703. // executeAlterTableDropColumn drops a column from a table.
  3704. func (e *Executor) executeAlterTableDropColumn(table string, action *parser.DropColumnAction) (*Result, error) {
  3705. if err := e.schema.DropColumn(table, action.Column); err != nil {
  3706. return nil, err
  3707. }
  3708. // Update catalog
  3709. e.SyncCatalog()
  3710. result := NewResult("ALTER TABLE")
  3711. return result, nil
  3712. }
  3713. // executeAlterTableRename renames a table.
  3714. func (e *Executor) executeAlterTableRename(table string, action *parser.RenameTableAction) (*Result, error) {
  3715. if err := e.schema.RenameTable(table, action.NewName); err != nil {
  3716. return nil, err
  3717. }
  3718. e.session.InvalidateCache(table)
  3719. e.session.InvalidateCache(action.NewName)
  3720. // Update catalog
  3721. e.SyncCatalog()
  3722. result := NewResult("ALTER TABLE")
  3723. return result, nil
  3724. }
  3725. // executeAlterTableRenameColumn renames a column.
  3726. func (e *Executor) executeAlterTableRenameColumn(table string, action *parser.RenameColumnAction) (*Result, error) {
  3727. if err := e.schema.RenameColumn(table, action.OldName, action.NewName); err != nil {
  3728. return nil, err
  3729. }
  3730. // Update catalog
  3731. e.SyncCatalog()
  3732. result := NewResult("ALTER TABLE")
  3733. return result, nil
  3734. }
  3735. // Transaction execution methods
  3736. // executeBegin starts a new transaction.
  3737. func (e *Executor) executeBegin(stmt *parser.BeginStmt) (*Result, error) {
  3738. if e.inTransaction {
  3739. return nil, fmt.Errorf("cannot start a transaction within a transaction")
  3740. }
  3741. if err := e.session.Begin(); err != nil {
  3742. return nil, err
  3743. }
  3744. e.inTransaction = true
  3745. e.savepoints = nil
  3746. e.savepointPositions = nil
  3747. result := NewResult("BEGIN")
  3748. return result, nil
  3749. }
  3750. // executeCommit commits the current transaction.
  3751. func (e *Executor) executeCommit(stmt *parser.CommitStmt) (*Result, error) {
  3752. if !e.inTransaction {
  3753. return nil, fmt.Errorf("cannot commit: no transaction in progress")
  3754. }
  3755. if err := e.session.Commit(); err != nil {
  3756. e.inTransaction = false
  3757. e.savepoints = nil
  3758. e.savepointPositions = nil
  3759. return nil, err
  3760. }
  3761. e.inTransaction = false
  3762. e.savepoints = nil
  3763. e.savepointPositions = nil
  3764. result := NewResult("COMMIT")
  3765. return result, nil
  3766. }
  3767. // executeRollback rolls back the current transaction or to a savepoint.
  3768. func (e *Executor) executeRollback(stmt *parser.RollbackStmt) (*Result, error) {
  3769. if !e.inTransaction {
  3770. return nil, fmt.Errorf("cannot rollback: no transaction in progress")
  3771. }
  3772. if stmt.Savepoint != "" {
  3773. // Rollback to savepoint
  3774. return e.rollbackToSavepoint(stmt.Savepoint)
  3775. }
  3776. if err := e.session.Rollback(); err != nil {
  3777. return nil, err
  3778. }
  3779. e.inTransaction = false
  3780. e.savepoints = nil
  3781. e.savepointPositions = nil
  3782. // total_changes() is monotonic (SQLite semantics): it is NOT decremented on
  3783. // rollback. last_insert_rowid() and changes() also intentionally hold.
  3784. result := NewResult("ROLLBACK")
  3785. return result, nil
  3786. }
  3787. // executeSavepoint creates a savepoint.
  3788. func (e *Executor) executeSavepoint(stmt *parser.SavepointStmt) (*Result, error) {
  3789. if !e.inTransaction {
  3790. // SQLite allows SAVEPOINT outside transaction (starts implicit transaction)
  3791. if err := e.session.Begin(); err != nil {
  3792. return nil, err
  3793. }
  3794. e.inTransaction = true
  3795. e.savepoints = nil
  3796. e.savepointPositions = nil
  3797. }
  3798. // Add savepoint marker
  3799. e.savepoints = append(e.savepoints, stmt.Name)
  3800. e.savepointPositions = append(e.savepointPositions, e.session.Snapshot())
  3801. result := NewResult("SAVEPOINT")
  3802. return result, nil
  3803. }
  3804. // executeRelease releases a savepoint.
  3805. func (e *Executor) executeRelease(stmt *parser.ReleaseStmt) (*Result, error) {
  3806. if !e.inTransaction {
  3807. return nil, fmt.Errorf("cannot release savepoint: no transaction in progress")
  3808. }
  3809. // Find and remove the savepoint
  3810. found := false
  3811. for i := len(e.savepoints) - 1; i >= 0; i-- {
  3812. if e.savepoints[i] == stmt.Name {
  3813. e.savepoints = e.savepoints[:i]
  3814. e.savepointPositions = e.savepointPositions[:i]
  3815. found = true
  3816. break
  3817. }
  3818. }
  3819. if !found {
  3820. return nil, fmt.Errorf("no such savepoint: %s", stmt.Name)
  3821. }
  3822. result := NewResult("RELEASE")
  3823. return result, nil
  3824. }
  3825. // executeAttach attaches a database.
  3826. func (e *Executor) executeAttach(stmt *parser.AttachStmt) (*Result, error) {
  3827. // Check if alias already exists
  3828. if _, exists := e.attachedDatabases[stmt.Alias]; exists {
  3829. return nil, fmt.Errorf("database alias already exists: %s", stmt.Alias)
  3830. }
  3831. // Reserved alias check
  3832. if strings.EqualFold(stmt.Alias, "temp") || strings.EqualFold(stmt.Alias, "temporary") {
  3833. return nil, fmt.Errorf("reserved database alias: %s", stmt.Alias)
  3834. }
  3835. // Get the pool from the main schema manager
  3836. pool := e.schema.GetPool()
  3837. // Create new schema and table managers for the attached database
  3838. // In PizzaKV, each database is just a different namespace/prefix
  3839. schema := storage.NewSchemaManager(pool, stmt.FilePath)
  3840. table := storage.NewTableManager(pool, schema, stmt.FilePath)
  3841. // Register the database connection
  3842. e.attachedDatabases[stmt.Alias] = &DatabaseConnection{
  3843. Alias: stmt.Alias,
  3844. Path: stmt.FilePath,
  3845. Schema: schema,
  3846. Table: table,
  3847. }
  3848. // Sync the catalog with the attached database's tables
  3849. tables, _ := schema.ListTables()
  3850. for _, tableName := range tables {
  3851. tSchema, err := schema.GetSchema(tableName)
  3852. if err != nil {
  3853. continue
  3854. }
  3855. // Add with database prefix
  3856. tableInfo := tSchema.ToAnalyzerTableInfo()
  3857. tableInfo.Name = stmt.Alias + "." + tableInfo.Name
  3858. e.catalog.CreateTable(tableInfo)
  3859. }
  3860. result := NewResult("ATTACH")
  3861. return result, nil
  3862. }
  3863. // executeDetach detaches a database.
  3864. func (e *Executor) executeDetach(stmt *parser.DetachStmt) (*Result, error) {
  3865. // Cannot detach main database
  3866. if strings.EqualFold(stmt.Alias, "main") {
  3867. return nil, fmt.Errorf("cannot detach main database")
  3868. }
  3869. // Check if database exists
  3870. if _, exists := e.attachedDatabases[stmt.Alias]; !exists {
  3871. return nil, fmt.Errorf("no such database: %s", stmt.Alias)
  3872. }
  3873. // Remove from attached databases
  3874. delete(e.attachedDatabases, stmt.Alias)
  3875. // Note: We don't remove from catalog as that would be more complex
  3876. // In a production system, we'd need to track which tables belong to which database
  3877. result := NewResult("DETACH")
  3878. return result, nil
  3879. }
  3880. // rollbackToSavepoint rolls back to a specific savepoint.
  3881. func (e *Executor) rollbackToSavepoint(name string) (*Result, error) {
  3882. // Find savepoint index
  3883. savepointIdx := -1
  3884. for i := len(e.savepoints) - 1; i >= 0; i-- {
  3885. if e.savepoints[i] == name {
  3886. savepointIdx = i
  3887. break
  3888. }
  3889. }
  3890. if savepointIdx == -1 {
  3891. return nil, fmt.Errorf("no such savepoint: %s", name)
  3892. }
  3893. logPosition := e.savepointPositions[savepointIdx]
  3894. e.session.RollbackTo(logPosition)
  3895. // Remove savepoints after the target
  3896. e.savepoints = e.savepoints[:savepointIdx+1]
  3897. e.savepointPositions = e.savepointPositions[:savepointIdx+1]
  3898. result := NewResult("ROLLBACK")
  3899. return result, nil
  3900. }
  3901. // RollbackActive rolls back an open transaction, such as when its client
  3902. // disconnects before sending COMMIT or ROLLBACK.
  3903. func (e *Executor) RollbackActive() error {
  3904. if !e.inTransaction {
  3905. return nil
  3906. }
  3907. _, err := e.executeRollback(&parser.RollbackStmt{})
  3908. return err
  3909. }
  3910. // extractIndexableCondition extracts column name and value from a simple equality condition.
  3911. // Returns (column, value, true) if the expression is column = literal.
  3912. func (e *Executor) extractIndexableCondition(expr parser.Expr) (string, interface{}, bool) {
  3913. binExpr, ok := expr.(*parser.BinaryExpr)
  3914. if !ok {
  3915. return "", nil, false
  3916. }
  3917. // Only handle equality for now
  3918. if binExpr.Op != lexer.TokenEq {
  3919. return "", nil, false
  3920. }
  3921. // Check for column = literal pattern
  3922. colRef, leftIsCol := binExpr.Left.(*parser.ColumnRef)
  3923. litExpr, rightIsLit := binExpr.Right.(*parser.LiteralExpr)
  3924. if leftIsCol && rightIsLit {
  3925. val, _ := e.evalLiteral(litExpr)
  3926. return colRef.Column, val, true
  3927. }
  3928. // Check for literal = column pattern
  3929. litExpr, leftIsLit := binExpr.Left.(*parser.LiteralExpr)
  3930. colRef, rightIsCol := binExpr.Right.(*parser.ColumnRef)
  3931. if leftIsLit && rightIsCol {
  3932. val, _ := e.evalLiteral(litExpr)
  3933. return colRef.Column, val, true
  3934. }
  3935. return "", nil, false
  3936. }
  3937. // executePragma executes a PRAGMA statement.
  3938. func (e *Executor) executePragma(stmt *parser.PragmaStmt) (*Result, error) {
  3939. switch stmt.Name {
  3940. case "table_info":
  3941. return e.pragmaTableInfo(stmt.Arg)
  3942. case "table_list":
  3943. return e.pragmaTableList()
  3944. case "database_list":
  3945. return e.pragmaDatabaseList()
  3946. case "version":
  3947. return e.pragmaVersion()
  3948. case "foreign_keys":
  3949. result := NewResult("PRAGMA")
  3950. if stmt.Value == nil {
  3951. result.AddColumn("foreign_keys")
  3952. result.AddRow(int64(0))
  3953. return result, nil
  3954. }
  3955. if ref, ok := stmt.Value.(*parser.ColumnRef); ok && strings.EqualFold(ref.Column, "off") {
  3956. return result, nil
  3957. }
  3958. if literal, ok := stmt.Value.(*parser.LiteralExpr); ok && literal.Value == "0" {
  3959. return result, nil
  3960. }
  3961. return nil, fmt.Errorf("PizzaSQL does not enforce foreign keys; only PRAGMA foreign_keys = OFF is supported")
  3962. default:
  3963. return nil, fmt.Errorf("unknown pragma: %s", stmt.Name)
  3964. }
  3965. }
  3966. // pragmaTableInfo returns column information for a table.
  3967. func (e *Executor) pragmaTableInfo(tableName string) (*Result, error) {
  3968. if tableName == "" {
  3969. return nil, fmt.Errorf("table_info requires a table name")
  3970. }
  3971. schema, err := e.schema.GetSchema(tableName)
  3972. if err != nil {
  3973. return nil, err
  3974. }
  3975. result := NewResult("PRAGMA")
  3976. result.AddColumn("cid")
  3977. result.AddColumn("name")
  3978. result.AddColumn("type")
  3979. result.AddColumn("notnull")
  3980. result.AddColumn("dflt_value")
  3981. result.AddColumn("pk")
  3982. for i, col := range schema.Columns {
  3983. notnull := 0
  3984. if !col.Nullable {
  3985. notnull = 1
  3986. }
  3987. pk := 0
  3988. if col.PrimaryKey {
  3989. pk = 1
  3990. }
  3991. result.AddRow(int64(i), col.Name, col.Type, int64(notnull), col.Default, int64(pk))
  3992. }
  3993. return result, nil
  3994. }
  3995. // pragmaTableList returns a list of all tables.
  3996. func (e *Executor) pragmaTableList() (*Result, error) {
  3997. tables, err := e.schema.ListTables()
  3998. if err != nil {
  3999. return nil, err
  4000. }
  4001. result := NewResult("PRAGMA")
  4002. result.AddColumn("schema")
  4003. result.AddColumn("name")
  4004. result.AddColumn("type")
  4005. for _, t := range tables {
  4006. result.AddRow("main", t, "table")
  4007. }
  4008. return result, nil
  4009. }
  4010. // pragmaDatabaseList returns a list of databases.
  4011. func (e *Executor) pragmaDatabaseList() (*Result, error) {
  4012. result := NewResult("PRAGMA")
  4013. result.AddColumn("seq")
  4014. result.AddColumn("name")
  4015. result.AddColumn("file")
  4016. // We only have one database
  4017. result.AddRow(int64(0), "main", "")
  4018. return result, nil
  4019. }
  4020. // pragmaVersion returns the PizzaSQL version.
  4021. func (e *Executor) pragmaVersion() (*Result, error) {
  4022. result := NewResult("PRAGMA")
  4023. result.AddColumn("version")
  4024. result.AddRow(version.String())
  4025. return result, nil
  4026. }
  4027. // executeExplain executes an EXPLAIN statement.
  4028. // executeAnalyze accepts ANALYZE as a documented no-op. PizzaSQL has no
  4029. // cost-based optimizer or persisted statistics, so there is nothing to gather;
  4030. // the statement exists so SQLite migrations that end with ANALYZE succeed.
  4031. func (e *Executor) executeAnalyze(stmt *parser.AnalyzeStmt) (*Result, error) {
  4032. return NewResult("ANALYZE"), nil
  4033. }
  4034. func (e *Executor) executeExplain(stmt *parser.ExplainStmt) (*Result, error) {
  4035. result := NewResult("EXPLAIN")
  4036. if stmt.QueryPlan {
  4037. // EXPLAIN QUERY PLAN format
  4038. result.AddColumn("id")
  4039. result.AddColumn("parent")
  4040. result.AddColumn("notused")
  4041. result.AddColumn("detail")
  4042. plan := e.generateQueryPlan(stmt.Statement)
  4043. for i, step := range plan {
  4044. result.AddRow(int64(i), int64(0), int64(0), step)
  4045. }
  4046. } else {
  4047. // Simple EXPLAIN format
  4048. result.AddColumn("addr")
  4049. result.AddColumn("opcode")
  4050. result.AddColumn("p1")
  4051. result.AddColumn("p2")
  4052. result.AddColumn("p3")
  4053. result.AddColumn("p4")
  4054. result.AddColumn("p5")
  4055. result.AddColumn("comment")
  4056. ops := e.generateOpcodes(stmt.Statement)
  4057. for i, op := range ops {
  4058. result.AddRow(int64(i), op, int64(0), int64(0), int64(0), "", int64(0), "")
  4059. }
  4060. }
  4061. return result, nil
  4062. }
  4063. // generateQueryPlan generates a simple query plan description.
  4064. func (e *Executor) generateQueryPlan(stmt parser.Statement) []string {
  4065. var plan []string
  4066. switch s := stmt.(type) {
  4067. case *parser.SelectStmt:
  4068. if len(s.From) > 0 {
  4069. plan = append(plan, fmt.Sprintf("SCAN TABLE %s", s.From[0].Name))
  4070. if s.Where != nil {
  4071. plan = append(plan, "FILTER")
  4072. }
  4073. if len(s.OrderBy) > 0 {
  4074. plan = append(plan, "SORT")
  4075. }
  4076. if s.Limit != nil {
  4077. plan = append(plan, "LIMIT")
  4078. }
  4079. } else {
  4080. plan = append(plan, "SCALAR EXPRESSION")
  4081. }
  4082. case *parser.InsertStmt:
  4083. plan = append(plan, fmt.Sprintf("INSERT INTO %s", s.Table.Name))
  4084. case *parser.UpdateStmt:
  4085. plan = append(plan, fmt.Sprintf("SCAN TABLE %s", s.Table.Name))
  4086. plan = append(plan, "UPDATE")
  4087. case *parser.DeleteStmt:
  4088. plan = append(plan, fmt.Sprintf("SCAN TABLE %s", s.Table.Name))
  4089. plan = append(plan, "DELETE")
  4090. default:
  4091. plan = append(plan, "EXECUTE")
  4092. }
  4093. return plan
  4094. }
  4095. // generateOpcodes generates simplified opcodes for EXPLAIN.
  4096. func (e *Executor) generateOpcodes(stmt parser.Statement) []string {
  4097. var ops []string
  4098. switch s := stmt.(type) {
  4099. case *parser.SelectStmt:
  4100. ops = append(ops, "Init")
  4101. if len(s.From) > 0 {
  4102. ops = append(ops, "OpenRead")
  4103. ops = append(ops, "Rewind")
  4104. ops = append(ops, "Column")
  4105. ops = append(ops, "ResultRow")
  4106. ops = append(ops, "Next")
  4107. ops = append(ops, "Close")
  4108. } else {
  4109. ops = append(ops, "Integer")
  4110. ops = append(ops, "ResultRow")
  4111. }
  4112. ops = append(ops, "Halt")
  4113. case *parser.InsertStmt:
  4114. ops = append(ops, "Init")
  4115. ops = append(ops, "OpenWrite")
  4116. ops = append(ops, "NewRowid")
  4117. ops = append(ops, "Insert")
  4118. ops = append(ops, "Close")
  4119. ops = append(ops, "Halt")
  4120. case *parser.UpdateStmt:
  4121. ops = append(ops, "Init")
  4122. ops = append(ops, "OpenWrite")
  4123. ops = append(ops, "Rewind")
  4124. ops = append(ops, "Column")
  4125. ops = append(ops, "Update")
  4126. ops = append(ops, "Next")
  4127. ops = append(ops, "Close")
  4128. ops = append(ops, "Halt")
  4129. case *parser.DeleteStmt:
  4130. ops = append(ops, "Init")
  4131. ops = append(ops, "OpenWrite")
  4132. ops = append(ops, "Rewind")
  4133. ops = append(ops, "Delete")
  4134. ops = append(ops, "Next")
  4135. ops = append(ops, "Close")
  4136. ops = append(ops, "Halt")
  4137. default:
  4138. ops = append(ops, "Init")
  4139. ops = append(ops, "Halt")
  4140. }
  4141. return ops
  4142. }
  4143. // evalExpr evaluates an expression.
  4144. func (e *Executor) evalExpr(expr parser.Expr, row storage.Row) (interface{}, error) {
  4145. if expr == nil {
  4146. return nil, nil
  4147. }
  4148. switch ex := expr.(type) {
  4149. case *parser.LiteralExpr:
  4150. return e.evalLiteral(ex)
  4151. case *parser.ColumnRef:
  4152. return e.evalColumnRef(ex, row)
  4153. case *parser.BinaryExpr:
  4154. return e.evalBinaryExpr(ex, row)
  4155. case *parser.UnaryExpr:
  4156. return e.evalUnaryExpr(ex, row)
  4157. case *parser.FunctionCall:
  4158. return e.evalFunctionCall(ex, row)
  4159. case *parser.ParenExpr:
  4160. return e.evalExpr(ex.Expr, row)
  4161. case *parser.CaseExpr:
  4162. return e.evalCaseExpr(ex, row)
  4163. case *parser.InExpr:
  4164. return e.evalInExpr(ex, row)
  4165. case *parser.BetweenExpr:
  4166. return e.evalBetweenExpr(ex, row)
  4167. case *parser.LikeExpr:
  4168. return e.evalLikeExpr(ex, row)
  4169. case *parser.IsNullExpr:
  4170. return e.evalIsNullExpr(ex, row)
  4171. case *parser.IsDistinctExpr:
  4172. return e.evalIsDistinctExpr(ex, row)
  4173. case *parser.CastExpr:
  4174. return e.evalCastExpr(ex, row)
  4175. case *parser.SubqueryExpr:
  4176. return e.evalSubqueryExpr(ex, row)
  4177. case *parser.ExistsExpr:
  4178. return e.evalExistsExpr(ex, row)
  4179. default:
  4180. return nil, fmt.Errorf("unsupported expression type: %T", expr)
  4181. }
  4182. }
  4183. func (e *Executor) evalLiteral(lit *parser.LiteralExpr) (interface{}, error) {
  4184. switch lit.Type {
  4185. case lexer.TokenNumber:
  4186. // Check for scientific notation (e.g., 1e+06) or decimal point
  4187. if strings.Contains(lit.Value, ".") || strings.ContainsAny(lit.Value, "eE") {
  4188. f, err := strconv.ParseFloat(lit.Value, 64)
  4189. if err != nil {
  4190. return nil, err
  4191. }
  4192. // If it's a whole number (no fractional part), return as int64
  4193. if f == float64(int64(f)) {
  4194. return int64(f), nil
  4195. }
  4196. return f, nil
  4197. }
  4198. return strconv.ParseInt(lit.Value, 10, 64)
  4199. case lexer.TokenString:
  4200. return lit.Value, nil
  4201. case lexer.TokenBlob:
  4202. // The lexer stores the decoded bytes in the literal, so a blob literal
  4203. // becomes a true []byte value.
  4204. return []byte(lit.Value), nil
  4205. case lexer.TokenNULL:
  4206. return nil, nil
  4207. case lexer.TokenTRUE:
  4208. return true, nil
  4209. case lexer.TokenFALSE:
  4210. return false, nil
  4211. default:
  4212. return lit.Value, nil
  4213. }
  4214. }
  4215. func (e *Executor) evalColumnRef(ref *parser.ColumnRef, row storage.Row) (interface{}, error) {
  4216. // SQLite date/time keywords (CURRENT_TIMESTAMP, CURRENT_DATE, CURRENT_TIME)
  4217. // are lexed as identifiers; resolve them when no real column shadows them.
  4218. if ref.Table == "" {
  4219. if _, has := lookupRowValue(row, ref.Column); !has {
  4220. if val, ok := sqliteCurrentTimeValue(ref.Column); ok {
  4221. return val, nil
  4222. }
  4223. }
  4224. }
  4225. if row == nil {
  4226. return nil, fmt.Errorf("no row context for column: %s", ref.Column)
  4227. }
  4228. // For qualified column references (table.column):
  4229. //
  4230. // Resolution order:
  4231. // 1. Exact qualified key in outer row ("t1.b" → outer)
  4232. // 2. Case-insensitive qualified in outer row
  4233. // 3. Exact qualified key in current row ("x.b" → inner alias)
  4234. // 4. Case-insensitive qualified in current row
  4235. // 5. Unqualified in outer row — only reached when qualified lookup in current
  4236. // row failed, meaning the qualifier refers to an outer table not the inner
  4237. // alias (e.g. "t1.b" in a subquery "FROM t1 AS x" resolves here).
  4238. // 6. Unqualified in current row (last resort)
  4239. if ref.Table != "" {
  4240. if e.outerRow != nil {
  4241. // Step 1-2: qualified lookup in outer row
  4242. if val, ok := e.outerRow[ref.Table+"."+ref.Column]; ok {
  4243. return val, nil
  4244. }
  4245. for k, v := range e.outerRow {
  4246. if strings.EqualFold(k, ref.Table+"."+ref.Column) {
  4247. return v, nil
  4248. }
  4249. }
  4250. }
  4251. // Step 3-4: qualified lookup in current row
  4252. if val, ok := row[ref.Table+"."+ref.Column]; ok {
  4253. return val, nil
  4254. }
  4255. for k, v := range row {
  4256. if strings.EqualFold(k, ref.Table+"."+ref.Column) {
  4257. return v, nil
  4258. }
  4259. }
  4260. // Step 5: qualified lookup failed in current row — try outer row unqualified.
  4261. // This handles correlated subqueries where the qualifier names an outer table
  4262. // (e.g. "t1.b" when the inner FROM is "t1 AS x", so current row has "x.b"
  4263. // but no "t1.b").
  4264. if e.outerRow != nil {
  4265. if val, ok := e.outerRow[ref.Column]; ok {
  4266. return val, nil
  4267. }
  4268. for k, v := range e.outerRow {
  4269. if strings.EqualFold(k, ref.Column) {
  4270. return v, nil
  4271. }
  4272. }
  4273. }
  4274. }
  4275. // Step 6: unqualified fallback in current row (handles unqualified refs and
  4276. // single-table queries like "SELECT t1.a FROM t1" where rows have plain keys).
  4277. if val, ok := row[ref.Column]; ok {
  4278. return val, nil
  4279. }
  4280. for k, v := range row {
  4281. if strings.EqualFold(k, ref.Column) {
  4282. return v, nil
  4283. }
  4284. }
  4285. // For unqualified refs with an outer row context (ref.Table == "").
  4286. if e.outerRow != nil && ref.Table == "" {
  4287. if val, ok := e.outerRow[ref.Column]; ok {
  4288. return val, nil
  4289. }
  4290. for k, v := range e.outerRow {
  4291. if strings.EqualFold(k, ref.Column) {
  4292. return v, nil
  4293. }
  4294. }
  4295. }
  4296. // Hidden rowid alias (rowid/oid/_rowid_): only used when the row carries no
  4297. // real column of that name. SQLite semantics give an explicit column named
  4298. // oid/rowid/_rowid_ precedence over the hidden rowid alias, so this fallback
  4299. // runs last.
  4300. if storage.IsRowIDColumn(ref.Column) {
  4301. if val, ok := row["_rowid_"]; ok {
  4302. return val, nil
  4303. }
  4304. }
  4305. return nil, nil // Column not found, return NULL
  4306. }
  4307. func (e *Executor) evalBinaryExpr(expr *parser.BinaryExpr, row storage.Row) (interface{}, error) {
  4308. left, err := e.evalExpr(expr.Left, row)
  4309. if err != nil {
  4310. return nil, err
  4311. }
  4312. right, err := e.evalExpr(expr.Right, row)
  4313. if err != nil {
  4314. return nil, err
  4315. }
  4316. if isBitwiseOp(expr.Op) {
  4317. if left == nil || right == nil {
  4318. return nil, nil
  4319. }
  4320. return applyBitwise(expr.Op, left, right)
  4321. }
  4322. switch expr.Op {
  4323. case lexer.TokenPlus:
  4324. if left == nil || right == nil {
  4325. return nil, nil
  4326. }
  4327. if isIntVal(left) && isIntVal(right) {
  4328. return toInt64(left) + toInt64(right), nil
  4329. }
  4330. return toFloat(left) + toFloat(right), nil
  4331. case lexer.TokenMinus:
  4332. if left == nil || right == nil {
  4333. return nil, nil
  4334. }
  4335. if isIntVal(left) && isIntVal(right) {
  4336. return toInt64(left) - toInt64(right), nil
  4337. }
  4338. return toFloat(left) - toFloat(right), nil
  4339. case lexer.TokenStar:
  4340. if left == nil || right == nil {
  4341. return nil, nil
  4342. }
  4343. if isIntVal(left) && isIntVal(right) {
  4344. return toInt64(left) * toInt64(right), nil
  4345. }
  4346. return toFloat(left) * toFloat(right), nil
  4347. case lexer.TokenSlash:
  4348. if left == nil || right == nil {
  4349. return nil, nil
  4350. }
  4351. // Integer division when both operands are integers (truncates toward zero, matching SQLite)
  4352. if isIntVal(left) && isIntVal(right) {
  4353. ri := toInt64(right)
  4354. if ri == 0 {
  4355. return nil, nil
  4356. }
  4357. return toInt64(left) / ri, nil
  4358. }
  4359. r := toFloat(right)
  4360. if r == 0 {
  4361. return nil, nil // Division by zero returns NULL
  4362. }
  4363. return toFloat(left) / r, nil
  4364. case lexer.TokenPercent:
  4365. if left == nil || right == nil {
  4366. return nil, nil
  4367. }
  4368. if isIntVal(left) && isIntVal(right) {
  4369. ri := toInt64(right)
  4370. if ri == 0 {
  4371. return nil, nil
  4372. }
  4373. return toInt64(left) % ri, nil
  4374. }
  4375. return int64(toFloat(left)) % int64(toFloat(right)), nil
  4376. case lexer.TokenEq:
  4377. if left == nil || right == nil {
  4378. return nil, nil
  4379. }
  4380. return compare(left, right) == 0, nil
  4381. case lexer.TokenNeq:
  4382. if left == nil || right == nil {
  4383. return nil, nil
  4384. }
  4385. return compare(left, right) != 0, nil
  4386. case lexer.TokenLt:
  4387. if left == nil || right == nil {
  4388. return nil, nil
  4389. }
  4390. return compare(left, right) < 0, nil
  4391. case lexer.TokenLte:
  4392. if left == nil || right == nil {
  4393. return nil, nil
  4394. }
  4395. return compare(left, right) <= 0, nil
  4396. case lexer.TokenGt:
  4397. if left == nil || right == nil {
  4398. return nil, nil
  4399. }
  4400. return compare(left, right) > 0, nil
  4401. case lexer.TokenGte:
  4402. if left == nil || right == nil {
  4403. return nil, nil
  4404. }
  4405. return compare(left, right) >= 0, nil
  4406. case lexer.TokenAND:
  4407. // Three-value logic: FALSE AND x = FALSE; NULL AND TRUE = NULL; TRUE AND TRUE = TRUE
  4408. if left != nil && !toBool(left) {
  4409. return false, nil
  4410. }
  4411. if right != nil && !toBool(right) {
  4412. return false, nil
  4413. }
  4414. if left == nil || right == nil {
  4415. return nil, nil
  4416. }
  4417. return true, nil
  4418. case lexer.TokenOR:
  4419. // Three-value logic: TRUE OR x = TRUE; NULL OR FALSE = NULL; FALSE OR FALSE = FALSE
  4420. if left != nil && toBool(left) {
  4421. return true, nil
  4422. }
  4423. if right != nil && toBool(right) {
  4424. return true, nil
  4425. }
  4426. if left == nil || right == nil {
  4427. return nil, nil
  4428. }
  4429. return false, nil
  4430. case lexer.TokenConcat:
  4431. return toString(left) + toString(right), nil
  4432. default:
  4433. return nil, fmt.Errorf("unsupported operator: %v", expr.Op)
  4434. }
  4435. }
  4436. // applyBinaryOp applies a binary operator to two already-evaluated values.
  4437. func (e *Executor) applyBinaryOp(op lexer.TokenType, left, right interface{}) (interface{}, error) {
  4438. if isBitwiseOp(op) {
  4439. if left == nil || right == nil {
  4440. return nil, nil
  4441. }
  4442. return applyBitwise(op, left, right)
  4443. }
  4444. switch op {
  4445. case lexer.TokenPlus:
  4446. if left == nil || right == nil {
  4447. return nil, nil
  4448. }
  4449. if isIntVal(left) && isIntVal(right) {
  4450. return toInt64(left) + toInt64(right), nil
  4451. }
  4452. return toFloat(left) + toFloat(right), nil
  4453. case lexer.TokenMinus:
  4454. if left == nil || right == nil {
  4455. return nil, nil
  4456. }
  4457. if isIntVal(left) && isIntVal(right) {
  4458. return toInt64(left) - toInt64(right), nil
  4459. }
  4460. return toFloat(left) - toFloat(right), nil
  4461. case lexer.TokenStar:
  4462. if left == nil || right == nil {
  4463. return nil, nil
  4464. }
  4465. if isIntVal(left) && isIntVal(right) {
  4466. return toInt64(left) * toInt64(right), nil
  4467. }
  4468. return toFloat(left) * toFloat(right), nil
  4469. case lexer.TokenSlash:
  4470. if left == nil || right == nil {
  4471. return nil, nil
  4472. }
  4473. if isIntVal(left) && isIntVal(right) {
  4474. ri := toInt64(right)
  4475. if ri == 0 {
  4476. return nil, nil
  4477. }
  4478. return toInt64(left) / ri, nil
  4479. }
  4480. r := toFloat(right)
  4481. if r == 0 {
  4482. return nil, nil
  4483. }
  4484. return toFloat(left) / r, nil
  4485. case lexer.TokenPercent:
  4486. if left == nil || right == nil {
  4487. return nil, nil
  4488. }
  4489. if isIntVal(left) && isIntVal(right) {
  4490. ri := toInt64(right)
  4491. if ri == 0 {
  4492. return nil, nil
  4493. }
  4494. return toInt64(left) % ri, nil
  4495. }
  4496. return int64(toFloat(left)) % int64(toFloat(right)), nil
  4497. case lexer.TokenEq:
  4498. if left == nil || right == nil {
  4499. return nil, nil
  4500. }
  4501. return compare(left, right) == 0, nil
  4502. case lexer.TokenNeq:
  4503. if left == nil || right == nil {
  4504. return nil, nil
  4505. }
  4506. return compare(left, right) != 0, nil
  4507. case lexer.TokenLt:
  4508. if left == nil || right == nil {
  4509. return nil, nil
  4510. }
  4511. return compare(left, right) < 0, nil
  4512. case lexer.TokenLte:
  4513. if left == nil || right == nil {
  4514. return nil, nil
  4515. }
  4516. return compare(left, right) <= 0, nil
  4517. case lexer.TokenGt:
  4518. if left == nil || right == nil {
  4519. return nil, nil
  4520. }
  4521. return compare(left, right) > 0, nil
  4522. case lexer.TokenGte:
  4523. if left == nil || right == nil {
  4524. return nil, nil
  4525. }
  4526. return compare(left, right) >= 0, nil
  4527. case lexer.TokenAND:
  4528. if left != nil && !toBool(left) {
  4529. return false, nil
  4530. }
  4531. if right != nil && !toBool(right) {
  4532. return false, nil
  4533. }
  4534. if left == nil || right == nil {
  4535. return nil, nil
  4536. }
  4537. return true, nil
  4538. case lexer.TokenOR:
  4539. if left != nil && toBool(left) {
  4540. return true, nil
  4541. }
  4542. if right != nil && toBool(right) {
  4543. return true, nil
  4544. }
  4545. if left == nil || right == nil {
  4546. return nil, nil
  4547. }
  4548. return false, nil
  4549. case lexer.TokenConcat:
  4550. return toString(left) + toString(right), nil
  4551. default:
  4552. return nil, fmt.Errorf("unsupported operator: %v", op)
  4553. }
  4554. }
  4555. // isBitwiseOp reports whether op is a SQLite bitwise operator.
  4556. func isBitwiseOp(op lexer.TokenType) bool {
  4557. switch op {
  4558. case lexer.TokenBitAnd, lexer.TokenBitOr, lexer.TokenShiftLeft, lexer.TokenShiftRight:
  4559. return true
  4560. }
  4561. return false
  4562. }
  4563. // applyBitwise applies a bitwise operator with SQLite semantics. Operands are
  4564. // coerced to integers; a negative shift reverses direction, and an
  4565. // out-of-range shift saturates.
  4566. func applyBitwise(op lexer.TokenType, left, right interface{}) (interface{}, error) {
  4567. li := toInt64(left)
  4568. ri := toInt64(right)
  4569. switch op {
  4570. case lexer.TokenBitAnd:
  4571. return li & ri, nil
  4572. case lexer.TokenBitOr:
  4573. return li | ri, nil
  4574. case lexer.TokenShiftLeft:
  4575. return bitShiftLeft(li, ri), nil
  4576. case lexer.TokenShiftRight:
  4577. return bitShiftRight(li, ri), nil
  4578. default:
  4579. return nil, fmt.Errorf("unsupported bitwise operator: %v", op)
  4580. }
  4581. }
  4582. func bitShiftLeft(v, shift int64) int64 {
  4583. if shift < 0 {
  4584. return bitShiftRight(v, -shift)
  4585. }
  4586. if shift >= 64 {
  4587. return 0
  4588. }
  4589. return v << uint(shift)
  4590. }
  4591. func bitShiftRight(v, shift int64) int64 {
  4592. if shift < 0 {
  4593. return bitShiftLeft(v, -shift)
  4594. }
  4595. if shift >= 64 {
  4596. if v < 0 {
  4597. return -1
  4598. }
  4599. return 0
  4600. }
  4601. return v >> uint(shift)
  4602. }
  4603. // evalBuiltinFunction applies a named scalar function to pre-evaluated args.
  4604. func (e *Executor) evalBuiltinFunction(name string, args []interface{}) (interface{}, error) {
  4605. switch name {
  4606. case "NULLIF":
  4607. if len(args) >= 2 && compare(args[0], args[1]) == 0 {
  4608. return nil, nil
  4609. }
  4610. if len(args) > 0 {
  4611. return args[0], nil
  4612. }
  4613. case "IFNULL", "NVL":
  4614. if len(args) >= 2 {
  4615. if args[0] == nil {
  4616. return args[1], nil
  4617. }
  4618. return args[0], nil
  4619. }
  4620. case "COALESCE":
  4621. for _, a := range args {
  4622. if a != nil {
  4623. return a, nil
  4624. }
  4625. }
  4626. return nil, nil
  4627. case "ABS":
  4628. if len(args) > 0 && args[0] != nil {
  4629. if isIntVal(args[0]) {
  4630. v := toInt64(args[0])
  4631. if v < 0 {
  4632. return -v, nil
  4633. }
  4634. return v, nil
  4635. }
  4636. v := toFloat(args[0])
  4637. if v < 0 {
  4638. return -v, nil
  4639. }
  4640. return v, nil
  4641. }
  4642. case "LENGTH":
  4643. if len(args) > 0 && args[0] != nil {
  4644. return int64(len(fmt.Sprintf("%v", args[0]))), nil
  4645. }
  4646. }
  4647. // Fall back: store pre-evaluated values in row and build column refs.
  4648. row := make(storage.Row, len(args))
  4649. fn := &parser.FunctionCall{Name: name}
  4650. for i, a := range args {
  4651. key := fmt.Sprintf("__arg%d__", i)
  4652. row[key] = a
  4653. fn.Args = append(fn.Args, &parser.ColumnRef{Column: key})
  4654. }
  4655. return e.evalFunctionCall(fn, row)
  4656. }
  4657. func (e *Executor) evalUnaryExpr(expr *parser.UnaryExpr, row storage.Row) (interface{}, error) {
  4658. val, err := e.evalExpr(expr.Operand, row)
  4659. if err != nil {
  4660. return nil, err
  4661. }
  4662. switch expr.Op {
  4663. case lexer.TokenMinus:
  4664. if val == nil {
  4665. return nil, nil
  4666. }
  4667. if isIntVal(val) {
  4668. return -toInt64(val), nil
  4669. }
  4670. return -toFloat(val), nil
  4671. case lexer.TokenPlus:
  4672. if val == nil {
  4673. return nil, nil
  4674. }
  4675. if isIntVal(val) {
  4676. return toInt64(val), nil
  4677. }
  4678. return toFloat(val), nil
  4679. case lexer.TokenNOT:
  4680. if val == nil {
  4681. return nil, nil // NOT NULL = NULL
  4682. }
  4683. return !toBool(val), nil
  4684. case lexer.TokenBitNot:
  4685. if val == nil {
  4686. return nil, nil
  4687. }
  4688. return ^toInt64(val), nil
  4689. default:
  4690. return val, nil
  4691. }
  4692. }
  4693. func (e *Executor) evalFunctionCall(fn *parser.FunctionCall, row storage.Row) (interface{}, error) {
  4694. name := strings.ToUpper(fn.Name)
  4695. // Evaluate arguments
  4696. args := make([]interface{}, len(fn.Args))
  4697. for i, arg := range fn.Args {
  4698. val, err := e.evalExpr(arg, row)
  4699. if err != nil {
  4700. return nil, err
  4701. }
  4702. args[i] = val
  4703. }
  4704. // JSON1 scalar functions are dispatched separately to keep this switch tidy.
  4705. if val, handled, err := evalJSONFunction(name, args); handled {
  4706. return val, err
  4707. }
  4708. switch name {
  4709. case "UPPER":
  4710. if len(args) > 0 {
  4711. if args[0] == nil {
  4712. return nil, nil // NULL propagation
  4713. }
  4714. return strings.ToUpper(toString(args[0])), nil
  4715. }
  4716. case "LOWER":
  4717. if len(args) > 0 {
  4718. if args[0] == nil {
  4719. return nil, nil // NULL propagation
  4720. }
  4721. return strings.ToLower(toString(args[0])), nil
  4722. }
  4723. case "LENGTH":
  4724. if len(args) > 0 {
  4725. if args[0] == nil {
  4726. return nil, nil // NULL propagation
  4727. }
  4728. return int64(len(toString(args[0]))), nil
  4729. }
  4730. case "ABS":
  4731. if len(args) > 0 {
  4732. if args[0] == nil {
  4733. return nil, nil
  4734. }
  4735. v := toFloat(args[0])
  4736. if v < 0 {
  4737. return -v, nil
  4738. }
  4739. return v, nil
  4740. }
  4741. case "COALESCE":
  4742. for _, arg := range args {
  4743. if arg != nil {
  4744. return arg, nil
  4745. }
  4746. }
  4747. return nil, nil
  4748. case "NULLIF":
  4749. if len(args) >= 2 && compare(args[0], args[1]) == 0 {
  4750. return nil, nil
  4751. }
  4752. if len(args) > 0 {
  4753. return args[0], nil
  4754. }
  4755. case "IFNULL":
  4756. if len(args) >= 2 {
  4757. if args[0] == nil {
  4758. return args[1], nil
  4759. }
  4760. return args[0], nil
  4761. }
  4762. case "TYPEOF":
  4763. if len(args) > 0 {
  4764. switch args[0].(type) {
  4765. case nil:
  4766. return "null", nil
  4767. case int64, int:
  4768. return "integer", nil
  4769. case float64:
  4770. return "real", nil
  4771. case string:
  4772. return "text", nil
  4773. case []byte:
  4774. return "blob", nil
  4775. default:
  4776. return "text", nil
  4777. }
  4778. }
  4779. case "SUBSTR", "SUBSTRING":
  4780. if len(args) >= 2 {
  4781. // SQLite substring semantics. Indices are 1-based and inclusive:
  4782. // a zero or negative Y shifts the window rather than simply
  4783. // clamping, e.g. substr('US-NY', 0, 3) is 'US', not 'US-'.
  4784. runes := []rune(toString(args[0]))
  4785. n := len(runes)
  4786. y := int(toFloat(args[1]))
  4787. var start1, end1 int
  4788. switch {
  4789. case y < 0:
  4790. start1 = n + y + 1
  4791. case y == 0:
  4792. start1 = 1
  4793. default:
  4794. start1 = y
  4795. }
  4796. if len(args) >= 3 {
  4797. z := int(toFloat(args[2]))
  4798. switch {
  4799. case z < 0:
  4800. end1 = start1 - 1
  4801. start1 = end1 + z + 1
  4802. case y < 0:
  4803. end1 = start1 + z - 1
  4804. case y == 0:
  4805. end1 = z - 1
  4806. default:
  4807. end1 = y + z - 1
  4808. }
  4809. } else {
  4810. end1 = n
  4811. }
  4812. if start1 < 1 {
  4813. start1 = 1
  4814. }
  4815. if end1 > n {
  4816. end1 = n
  4817. }
  4818. if start1 > n || start1 > end1 {
  4819. return "", nil
  4820. }
  4821. return string(runes[start1-1 : end1]), nil
  4822. }
  4823. case "TRIM":
  4824. if len(args) > 0 {
  4825. return strings.TrimSpace(toString(args[0])), nil
  4826. }
  4827. case "REPLACE":
  4828. if len(args) >= 3 {
  4829. return strings.ReplaceAll(toString(args[0]), toString(args[1]), toString(args[2])), nil
  4830. }
  4831. // Additional SQLite functions
  4832. case "PRINTF":
  4833. if len(args) > 0 {
  4834. format := toString(args[0])
  4835. fmtArgs := make([]interface{}, len(args)-1)
  4836. for i := 1; i < len(args); i++ {
  4837. fmtArgs[i-1] = args[i]
  4838. }
  4839. return fmt.Sprintf(format, fmtArgs...), nil
  4840. }
  4841. case "HEX":
  4842. if len(args) > 0 {
  4843. if args[0] == nil {
  4844. return nil, nil
  4845. }
  4846. if b, ok := args[0].([]byte); ok {
  4847. return strings.ToUpper(fmt.Sprintf("%x", b)), nil
  4848. }
  4849. return strings.ToUpper(fmt.Sprintf("%x", []byte(toString(args[0])))), nil
  4850. }
  4851. case "UNHEX":
  4852. if len(args) > 0 {
  4853. if args[0] == nil {
  4854. return nil, nil
  4855. }
  4856. s := toString(args[0])
  4857. result, err := hex.DecodeString(strings.TrimSpace(s))
  4858. if err != nil {
  4859. return nil, nil
  4860. }
  4861. return result, nil
  4862. }
  4863. case "RANDOM":
  4864. return rand.Int63(), nil
  4865. case "RANDOMBLOB":
  4866. if len(args) > 0 {
  4867. n := int(toFloat(args[0]))
  4868. if n <= 0 {
  4869. n = 1
  4870. }
  4871. if n > 1000000 {
  4872. n = 1000000
  4873. }
  4874. blob := make([]byte, n)
  4875. rand.Read(blob)
  4876. return blob, nil
  4877. }
  4878. case "ZEROBLOB":
  4879. if len(args) > 0 {
  4880. n := int(toFloat(args[0]))
  4881. if n <= 0 {
  4882. n = 1
  4883. }
  4884. if n > 1000000 {
  4885. n = 1000000
  4886. }
  4887. return make([]byte, n), nil
  4888. }
  4889. case "INSTR":
  4890. if len(args) >= 2 {
  4891. s := toString(args[0])
  4892. substr := toString(args[1])
  4893. idx := strings.Index(s, substr)
  4894. if idx < 0 {
  4895. return int64(0), nil
  4896. }
  4897. return int64(idx + 1), nil // SQL is 1-indexed
  4898. }
  4899. case "GLOB":
  4900. if len(args) >= 2 {
  4901. pattern := toString(args[0])
  4902. s := toString(args[1])
  4903. return matchGlob(pattern, s), nil
  4904. }
  4905. case "ROUND":
  4906. if len(args) > 0 {
  4907. v := toFloat(args[0])
  4908. decimals := 0
  4909. if len(args) >= 2 {
  4910. decimals = int(toFloat(args[1]))
  4911. }
  4912. mult := 1.0
  4913. for i := 0; i < decimals; i++ {
  4914. mult *= 10
  4915. }
  4916. return float64(int64(v*mult+0.5)) / mult, nil
  4917. }
  4918. case "MAX":
  4919. if len(args) > 0 {
  4920. max := args[0]
  4921. for _, arg := range args[1:] {
  4922. if compare(arg, max) > 0 {
  4923. max = arg
  4924. }
  4925. }
  4926. return max, nil
  4927. }
  4928. case "MIN":
  4929. if len(args) > 0 {
  4930. min := args[0]
  4931. for _, arg := range args[1:] {
  4932. if compare(arg, min) < 0 {
  4933. min = arg
  4934. }
  4935. }
  4936. return min, nil
  4937. }
  4938. case "CONCAT":
  4939. var result strings.Builder
  4940. for _, arg := range args {
  4941. result.WriteString(toString(arg))
  4942. }
  4943. return result.String(), nil
  4944. // Date/Time functions
  4945. case "DATE":
  4946. return evalDateFunc(args)
  4947. case "TIME":
  4948. return evalTimeFunc(args)
  4949. case "DATETIME":
  4950. return evalDatetimeFunc(args)
  4951. case "JULIANDAY":
  4952. return evalJuliandayFunc(args)
  4953. case "UNIXEPOCH":
  4954. return evalUnixepochFunc(args)
  4955. case "STRFTIME":
  4956. return evalStrftimeFunc(args)
  4957. case "TIMEDIFF":
  4958. return evalTimediffFunc(args)
  4959. case "PERCENT_DIFF":
  4960. return evalPercentDiff(args)
  4961. case "PIZZASQL_VERSION":
  4962. return version.String(), nil
  4963. case "SQLITE_VERSION":
  4964. return SQLiteCompatVersion, nil
  4965. case "LAST_INSERT_ROWID":
  4966. return e.lastInsertRowID, nil
  4967. case "CHANGES":
  4968. return e.changes, nil
  4969. case "TOTAL_CHANGES":
  4970. return e.totalChanges, nil
  4971. }
  4972. return nil, nil
  4973. }
  4974. func (e *Executor) evalCaseExpr(expr *parser.CaseExpr, row storage.Row) (interface{}, error) {
  4975. var operand interface{}
  4976. if expr.Operand != nil {
  4977. var err error
  4978. operand, err = e.evalExpr(expr.Operand, row)
  4979. if err != nil {
  4980. return nil, err
  4981. }
  4982. }
  4983. for _, when := range expr.Whens {
  4984. cond, err := e.evalExpr(when.Condition, row)
  4985. if err != nil {
  4986. return nil, err
  4987. }
  4988. var match bool
  4989. if expr.Operand != nil {
  4990. // Simple CASE: CASE operand WHEN val THEN ... — NULL operand matches nothing
  4991. if operand == nil {
  4992. continue
  4993. }
  4994. match = compare(operand, cond) == 0
  4995. } else {
  4996. // Searched CASE: CASE WHEN cond THEN ... — NULL condition is falsy
  4997. match = toBool(cond)
  4998. }
  4999. if match {
  5000. return e.evalExpr(when.Result, row)
  5001. }
  5002. }
  5003. if expr.Else != nil {
  5004. return e.evalExpr(expr.Else, row)
  5005. }
  5006. return nil, nil
  5007. }
  5008. func (e *Executor) evalInExpr(expr *parser.InExpr, row storage.Row) (interface{}, error) {
  5009. left, err := e.evalExpr(expr.Left, row)
  5010. if err != nil {
  5011. return nil, err
  5012. }
  5013. // Handle subquery: IN (SELECT ...)
  5014. if expr.Subquery != nil {
  5015. var result *Result
  5016. var err error
  5017. // Cache non-correlated subquery results for the duration of this query.
  5018. // Safe when outerRow is nil (no outer context that the subquery could reference).
  5019. if e.subqueryCache != nil && e.outerRow == nil {
  5020. if cached, ok := e.subqueryCache[expr.Subquery]; ok {
  5021. result = cached
  5022. } else {
  5023. result, err = e.executeSelect(expr.Subquery)
  5024. if err == nil {
  5025. e.subqueryCache[expr.Subquery] = result
  5026. }
  5027. }
  5028. } else {
  5029. result, err = e.executeSelect(expr.Subquery)
  5030. }
  5031. if err != nil {
  5032. return nil, fmt.Errorf("IN subquery error: %w", err)
  5033. }
  5034. if len(result.Columns) != 1 {
  5035. return nil, fmt.Errorf("subquery in IN must return exactly one column")
  5036. }
  5037. // SQL three-valued logic: if left is NULL → NULL; if any match → true; if any NULL → NULL; else false.
  5038. if left == nil {
  5039. return nil, nil
  5040. }
  5041. sawNull := false
  5042. for _, resultRow := range result.Rows {
  5043. if len(resultRow) == 0 {
  5044. continue
  5045. }
  5046. v := resultRow[0]
  5047. if v == nil {
  5048. sawNull = true
  5049. continue
  5050. }
  5051. if compare(left, v) == 0 {
  5052. if expr.Not {
  5053. return false, nil
  5054. }
  5055. return true, nil
  5056. }
  5057. }
  5058. if sawNull {
  5059. return nil, nil
  5060. }
  5061. if expr.Not {
  5062. return true, nil
  5063. }
  5064. return false, nil
  5065. }
  5066. // Handle value list: IN (1, 2, 3).
  5067. // Empty list: always FALSE (IN) / TRUE (NOT IN), even for NULL.
  5068. if len(expr.Values) == 0 {
  5069. return expr.Not, nil
  5070. }
  5071. // SQL three-valued logic: if left is NULL → NULL; if any match → true/false;
  5072. // if list contains NULL and no match → NULL.
  5073. if left == nil {
  5074. return nil, nil
  5075. }
  5076. sawNull := false
  5077. for _, val := range expr.Values {
  5078. v, err := e.evalExpr(val, row)
  5079. if err != nil {
  5080. return nil, err
  5081. }
  5082. if v == nil {
  5083. sawNull = true
  5084. continue
  5085. }
  5086. if compare(left, v) == 0 {
  5087. if expr.Not {
  5088. return false, nil
  5089. }
  5090. return true, nil
  5091. }
  5092. }
  5093. if sawNull {
  5094. return nil, nil
  5095. }
  5096. if expr.Not {
  5097. return true, nil
  5098. }
  5099. return false, nil
  5100. }
  5101. func (e *Executor) evalBetweenExpr(expr *parser.BetweenExpr, row storage.Row) (interface{}, error) {
  5102. val, err := e.evalExpr(expr.Left, row)
  5103. if err != nil {
  5104. return nil, err
  5105. }
  5106. low, err := e.evalExpr(expr.Low, row)
  5107. if err != nil {
  5108. return nil, err
  5109. }
  5110. high, err := e.evalExpr(expr.High, row)
  5111. if err != nil {
  5112. return nil, err
  5113. }
  5114. if expr.Not {
  5115. // NOT BETWEEN is equivalent to: val < low OR val > high
  5116. // We need to handle NULL using three-valued OR logic:
  5117. // NULL OR TRUE = TRUE
  5118. // NULL OR FALSE = NULL
  5119. // NULL OR NULL = NULL
  5120. var lessThan, greaterThan interface{}
  5121. if val == nil || low == nil {
  5122. lessThan = nil // NULL
  5123. } else {
  5124. lessThan = compare(val, low) < 0
  5125. }
  5126. if val == nil || high == nil {
  5127. greaterThan = nil // NULL
  5128. } else {
  5129. greaterThan = compare(val, high) > 0
  5130. }
  5131. // Implement three-valued OR
  5132. if toBool(lessThan) || toBool(greaterThan) {
  5133. return true, nil
  5134. }
  5135. if lessThan == nil || greaterThan == nil {
  5136. return nil, nil // NULL
  5137. }
  5138. return false, nil
  5139. } else {
  5140. // BETWEEN is equivalent to: val >= low AND val <= high
  5141. // Three-value logic: if val < low → FALSE (regardless of high); if val >= low and high is NULL → NULL
  5142. if val == nil {
  5143. return nil, nil
  5144. }
  5145. // x BETWEEN a AND b = (x >= a) AND (x <= b)
  5146. // NULL AND FALSE = FALSE; NULL AND TRUE = NULL
  5147. if low == nil {
  5148. // x >= NULL = NULL; check upper bound for early FALSE
  5149. if high != nil && compare(val, high) > 0 {
  5150. return false, nil // NULL AND FALSE = FALSE
  5151. }
  5152. return nil, nil // NULL AND TRUE/NULL = NULL
  5153. }
  5154. if compare(val, low) < 0 {
  5155. return false, nil // val < low → FALSE AND anything = FALSE
  5156. }
  5157. if high == nil {
  5158. return nil, nil // TRUE AND NULL = NULL
  5159. }
  5160. return compare(val, high) <= 0, nil
  5161. }
  5162. }
  5163. func (e *Executor) evalLikeExpr(expr *parser.LikeExpr, row storage.Row) (interface{}, error) {
  5164. val, err := e.evalExpr(expr.Left, row)
  5165. if err != nil {
  5166. return nil, err
  5167. }
  5168. pattern, err := e.evalExpr(expr.Pattern, row)
  5169. if err != nil {
  5170. return nil, err
  5171. }
  5172. s := toString(val)
  5173. p := toString(pattern)
  5174. // Convert SQL LIKE pattern to simple matching
  5175. // % matches any sequence, _ matches single character
  5176. matched := matchLike(s, p)
  5177. if expr.Not {
  5178. return !matched, nil
  5179. }
  5180. return matched, nil
  5181. }
  5182. func (e *Executor) evalIsNullExpr(expr *parser.IsNullExpr, row storage.Row) (interface{}, error) {
  5183. val, err := e.evalExpr(expr.Left, row)
  5184. if err != nil {
  5185. return nil, err
  5186. }
  5187. isNull := val == nil
  5188. if expr.Not {
  5189. return !isNull, nil
  5190. }
  5191. return isNull, nil
  5192. }
  5193. // evalIsDistinctExpr implements `a IS [NOT] DISTINCT FROM b`. It treats NULL as a
  5194. // comparable value: two NULLs are not distinct, and NULL is distinct from any
  5195. // non-NULL.
  5196. func (e *Executor) evalIsDistinctExpr(expr *parser.IsDistinctExpr, row storage.Row) (interface{}, error) {
  5197. left, err := e.evalExpr(expr.Left, row)
  5198. if err != nil {
  5199. return nil, err
  5200. }
  5201. right, err := e.evalExpr(expr.Right, row)
  5202. if err != nil {
  5203. return nil, err
  5204. }
  5205. distinct := false
  5206. switch {
  5207. case left == nil && right == nil:
  5208. distinct = false
  5209. case left == nil || right == nil:
  5210. distinct = true
  5211. default:
  5212. distinct = compare(left, right) != 0
  5213. }
  5214. if expr.Not {
  5215. return !distinct, nil
  5216. }
  5217. return distinct, nil
  5218. }
  5219. func (e *Executor) evalCastExpr(expr *parser.CastExpr, row storage.Row) (interface{}, error) {
  5220. val, err := e.evalExpr(expr.Expr, row)
  5221. if err != nil {
  5222. return nil, err
  5223. }
  5224. if val == nil {
  5225. return nil, nil // CAST(NULL AS any) = NULL
  5226. }
  5227. typeName := strings.ToUpper(expr.Type.Name)
  5228. switch {
  5229. case strings.Contains(typeName, "INT"):
  5230. return int64(toFloat(val)), nil
  5231. case strings.Contains(typeName, "REAL"), strings.Contains(typeName, "FLOAT"), strings.Contains(typeName, "DOUBLE"):
  5232. return toFloat(val), nil
  5233. case strings.Contains(typeName, "BLOB"):
  5234. if b, ok := val.([]byte); ok {
  5235. return b, nil
  5236. }
  5237. return []byte(toString(val)), nil
  5238. case strings.Contains(typeName, "TEXT"), strings.Contains(typeName, "CHAR"):
  5239. return toString(val), nil
  5240. default:
  5241. return val, nil
  5242. }
  5243. }
  5244. // evalSubqueryExpr executes a scalar subquery and returns its value.
  5245. // A scalar subquery must return exactly one column. It returns:
  5246. // - The single value if the subquery returns one row
  5247. // - NULL if the subquery returns no rows
  5248. // - Error if the subquery returns more than one row (for strict SQL compliance)
  5249. func (e *Executor) evalSubqueryExpr(expr *parser.SubqueryExpr, row storage.Row) (interface{}, error) {
  5250. if row != nil && e.correlatedAggCache != nil {
  5251. if val, ok, err := e.evalDecorrelatedAggSubquery(expr.Query, row); ok || err != nil {
  5252. return val, err
  5253. }
  5254. }
  5255. // Save and set outer row context for correlated subqueries
  5256. savedOuter := e.outerRow
  5257. e.outerRow = row
  5258. defer func() { e.outerRow = savedOuter }()
  5259. // Execute the subquery
  5260. result, err := e.executeSelect(expr.Query)
  5261. if err != nil {
  5262. return nil, fmt.Errorf("subquery error: %w", err)
  5263. }
  5264. // Check for empty result
  5265. if result.RowCount == 0 {
  5266. return nil, nil // Return NULL for empty subquery
  5267. }
  5268. // Check column count
  5269. if len(result.Columns) == 0 {
  5270. return nil, fmt.Errorf("subquery must return at least one column")
  5271. }
  5272. // For scalar subquery, return first column of first row
  5273. // Note: Strict SQL would error if more than one row is returned
  5274. // but we follow SQLite behavior which just returns the first value
  5275. if len(result.Rows) > 0 && len(result.Rows[0]) > 0 {
  5276. return result.Rows[0][0], nil
  5277. }
  5278. return nil, nil
  5279. }
  5280. func (e *Executor) evalDecorrelatedAggSubquery(query *parser.SelectStmt, outerRow storage.Row) (interface{}, bool, error) {
  5281. spec, ok := e.correlatedAggSpec(query)
  5282. if !ok {
  5283. return nil, false, nil
  5284. }
  5285. outerVal, err := e.evalExpr(spec.outerKey, outerRow)
  5286. if err != nil {
  5287. return nil, true, err
  5288. }
  5289. cache, exists := e.correlatedAggCache[query]
  5290. if !exists {
  5291. cache, err = e.buildCorrelatedAggCache(query, spec)
  5292. if err != nil {
  5293. return nil, true, err
  5294. }
  5295. e.correlatedAggCache[query] = cache
  5296. }
  5297. if outerVal == nil {
  5298. return cache.defaultValue, true, nil
  5299. }
  5300. if val, exists := cache.values[fmt.Sprintf("%v", outerVal)]; exists {
  5301. return val, true, nil
  5302. }
  5303. return cache.defaultValue, true, nil
  5304. }
  5305. func (e *Executor) correlatedAggSpec(query *parser.SelectStmt) (correlatedAggSpec, bool) {
  5306. if query == nil ||
  5307. query.Compound != nil ||
  5308. len(query.Columns) != 1 ||
  5309. len(query.From) == 0 ||
  5310. query.Where == nil ||
  5311. len(query.GroupBy) > 0 ||
  5312. query.Having != nil ||
  5313. query.Limit != nil ||
  5314. query.Offset != nil {
  5315. return correlatedAggSpec{}, false
  5316. }
  5317. if query.Columns[0].Star {
  5318. return correlatedAggSpec{}, false
  5319. }
  5320. agg, ok := query.Columns[0].Expr.(*parser.FunctionCall)
  5321. if !ok {
  5322. return correlatedAggSpec{}, false
  5323. }
  5324. switch strings.ToUpper(agg.Name) {
  5325. case "COUNT", "SUM", "AVG", "MIN", "MAX":
  5326. default:
  5327. return correlatedAggSpec{}, false
  5328. }
  5329. innerAliases := collectFromAliases(query.From)
  5330. bin, ok := query.Where.(*parser.BinaryExpr)
  5331. if !ok || bin.Op != lexer.TokenEq {
  5332. return correlatedAggSpec{}, false
  5333. }
  5334. leftRef, leftIsRef := bin.Left.(*parser.ColumnRef)
  5335. rightRef, rightIsRef := bin.Right.(*parser.ColumnRef)
  5336. if !leftIsRef || !rightIsRef {
  5337. return correlatedAggSpec{}, false
  5338. }
  5339. leftInner := refBelongsToAliases(leftRef, innerAliases)
  5340. rightInner := refBelongsToAliases(rightRef, innerAliases)
  5341. if leftInner == rightInner {
  5342. return correlatedAggSpec{}, false
  5343. }
  5344. if leftInner {
  5345. return correlatedAggSpec{innerKey: leftRef, outerKey: rightRef, aggExpr: agg}, true
  5346. }
  5347. return correlatedAggSpec{innerKey: rightRef, outerKey: leftRef, aggExpr: agg}, true
  5348. }
  5349. func (e *Executor) buildCorrelatedAggCache(query *parser.SelectStmt, spec correlatedAggSpec) (*correlatedAggCache, error) {
  5350. grouped := *query
  5351. grouped.Where = nil
  5352. grouped.GroupBy = []parser.Expr{spec.innerKey}
  5353. grouped.Having = nil
  5354. grouped.OrderBy = nil
  5355. grouped.Limit = nil
  5356. grouped.Offset = nil
  5357. grouped.Columns = []parser.SelectColumn{
  5358. {Expr: spec.innerKey, Alias: "__corr_key"},
  5359. {Expr: spec.aggExpr, Alias: "__corr_value"},
  5360. }
  5361. savedOuter := e.outerRow
  5362. e.outerRow = nil
  5363. result, err := e.executeSelect(&grouped)
  5364. e.outerRow = savedOuter
  5365. if err != nil {
  5366. return nil, fmt.Errorf("decorrelated aggregate subquery error: %w", err)
  5367. }
  5368. cache := &correlatedAggCache{
  5369. values: make(map[string]interface{}, len(result.Rows)),
  5370. defaultValue: correlatedAggDefault(spec.aggExpr),
  5371. }
  5372. for _, row := range result.Rows {
  5373. if len(row) < 2 || row[0] == nil {
  5374. continue
  5375. }
  5376. cache.values[fmt.Sprintf("%v", row[0])] = row[1]
  5377. }
  5378. return cache, nil
  5379. }
  5380. func correlatedAggDefault(expr parser.Expr) interface{} {
  5381. if fn, ok := expr.(*parser.FunctionCall); ok && strings.EqualFold(fn.Name, "COUNT") {
  5382. return int64(0)
  5383. }
  5384. return nil
  5385. }
  5386. func collectFromAliases(from []parser.TableRef) map[string]struct{} {
  5387. aliases := make(map[string]struct{})
  5388. var addRef func(parser.TableRef)
  5389. addRef = func(ref parser.TableRef) {
  5390. if ref.Name != "" {
  5391. aliases[strings.ToLower(ref.Name)] = struct{}{}
  5392. }
  5393. if ref.Alias != "" {
  5394. aliases[strings.ToLower(ref.Alias)] = struct{}{}
  5395. }
  5396. if ref.Join != nil && ref.Join.Table != nil {
  5397. addRef(*ref.Join.Table)
  5398. }
  5399. }
  5400. for _, ref := range from {
  5401. addRef(ref)
  5402. }
  5403. return aliases
  5404. }
  5405. func refBelongsToAliases(ref *parser.ColumnRef, aliases map[string]struct{}) bool {
  5406. if ref == nil || ref.Table == "" {
  5407. return false
  5408. }
  5409. _, ok := aliases[strings.ToLower(ref.Table)]
  5410. return ok
  5411. }
  5412. // evalExistsExpr evaluates an EXISTS expression.
  5413. // Returns true if the subquery returns at least one row, false otherwise.
  5414. func (e *Executor) evalExistsExpr(expr *parser.ExistsExpr, row storage.Row) (interface{}, error) {
  5415. // Save and set outer row context for correlated subqueries
  5416. savedOuter := e.outerRow
  5417. e.outerRow = row
  5418. defer func() { e.outerRow = savedOuter }()
  5419. // Execute the subquery
  5420. result, err := e.executeSelect(expr.Subquery)
  5421. if err != nil {
  5422. return nil, fmt.Errorf("EXISTS subquery error: %w", err)
  5423. }
  5424. // EXISTS returns true if any rows are returned
  5425. return len(result.Rows) > 0, nil
  5426. }
  5427. // evalAggregateExpr evaluates an aggregate expression over multiple rows.
  5428. func (e *Executor) evalAggregateExpr(expr parser.Expr, rows []storage.Row) (interface{}, error) {
  5429. fn, ok := expr.(*parser.FunctionCall)
  5430. if !ok {
  5431. // Not a function call - could be a binary expression with aggregates inside
  5432. // Evaluate it with the aggregate evaluation context
  5433. return e.evalExprWithAggregates(expr, rows)
  5434. }
  5435. name := strings.ToUpper(fn.Name)
  5436. switch name {
  5437. case "COUNT":
  5438. if fn.Star {
  5439. return int64(len(rows)), nil
  5440. }
  5441. if fn.Distinct {
  5442. seen := make(map[interface{}]struct{})
  5443. for _, row := range rows {
  5444. if len(fn.Args) > 0 {
  5445. val, _ := e.evalExpr(fn.Args[0], row)
  5446. if val != nil {
  5447. seen[val] = struct{}{}
  5448. }
  5449. }
  5450. }
  5451. return int64(len(seen)), nil
  5452. }
  5453. count := int64(0)
  5454. for _, row := range rows {
  5455. if len(fn.Args) > 0 {
  5456. val, _ := e.evalExpr(fn.Args[0], row)
  5457. if val != nil {
  5458. count++
  5459. }
  5460. }
  5461. }
  5462. return count, nil
  5463. case "SUM":
  5464. var sumInt int64
  5465. var sumFloat float64
  5466. allInt := true
  5467. hasValues := false
  5468. var seen map[interface{}]struct{}
  5469. if fn.Distinct {
  5470. seen = make(map[interface{}]struct{})
  5471. }
  5472. for _, row := range rows {
  5473. if len(fn.Args) > 0 {
  5474. val, _ := e.evalExpr(fn.Args[0], row)
  5475. if val != nil {
  5476. if fn.Distinct {
  5477. key := fmt.Sprintf("%v", val)
  5478. if _, exists := seen[key]; exists {
  5479. continue
  5480. }
  5481. seen[key] = struct{}{}
  5482. }
  5483. if isIntVal(val) {
  5484. sumInt += toInt64(val)
  5485. } else {
  5486. allInt = false
  5487. sumFloat += toFloat(val)
  5488. }
  5489. hasValues = true
  5490. }
  5491. }
  5492. }
  5493. if !hasValues {
  5494. return nil, nil
  5495. }
  5496. if allInt {
  5497. return sumInt, nil
  5498. }
  5499. return sumFloat + float64(sumInt), nil
  5500. case "AVG":
  5501. var sum float64
  5502. count := 0
  5503. for _, row := range rows {
  5504. if len(fn.Args) > 0 {
  5505. val, _ := e.evalExpr(fn.Args[0], row)
  5506. if val != nil {
  5507. sum += toFloat(val)
  5508. count++
  5509. }
  5510. }
  5511. }
  5512. if count == 0 {
  5513. return nil, nil
  5514. }
  5515. return sum / float64(count), nil
  5516. case "MIN":
  5517. var min interface{}
  5518. for _, row := range rows {
  5519. if len(fn.Args) > 0 {
  5520. val, _ := e.evalExpr(fn.Args[0], row)
  5521. if val != nil && (min == nil || compare(val, min) < 0) {
  5522. min = val
  5523. }
  5524. }
  5525. }
  5526. return min, nil
  5527. case "MAX":
  5528. var max interface{}
  5529. for _, row := range rows {
  5530. if len(fn.Args) > 0 {
  5531. val, _ := e.evalExpr(fn.Args[0], row)
  5532. if val != nil && (max == nil || compare(val, max) > 0) {
  5533. max = val
  5534. }
  5535. }
  5536. }
  5537. return max, nil
  5538. case "JSON_GROUP_ARRAY", "JSONB_GROUP_ARRAY":
  5539. arr := make([]interface{}, 0, len(rows))
  5540. var seen map[string]struct{}
  5541. if fn.Distinct {
  5542. seen = make(map[string]struct{})
  5543. }
  5544. for _, row := range rows {
  5545. var val interface{}
  5546. if len(fn.Args) > 0 {
  5547. val, _ = e.evalExpr(fn.Args[0], row)
  5548. }
  5549. if fn.Distinct {
  5550. key := fmt.Sprintf("%v", val)
  5551. if _, exists := seen[key]; exists {
  5552. continue
  5553. }
  5554. seen[key] = struct{}{}
  5555. }
  5556. arr = append(arr, jsonArgToNode(val))
  5557. }
  5558. s, err := jsonEncode(arr)
  5559. if err != nil {
  5560. return nil, err
  5561. }
  5562. return jsonText(s), nil
  5563. default:
  5564. // Non-aggregate scalar function: evaluate args through aggregate context
  5565. // (so COUNT/MIN/etc. inside NULLIF/COALESCE work correctly).
  5566. return e.evalExprWithAggregates(expr, rows)
  5567. }
  5568. }
  5569. // evalExprWithAggregates evaluates an expression that may contain aggregate functions
  5570. func (e *Executor) evalExprWithAggregates(expr parser.Expr, rows []storage.Row) (interface{}, error) {
  5571. switch ex := expr.(type) {
  5572. case *parser.BinaryExpr:
  5573. left, err := e.evalExprWithAggregates(ex.Left, rows)
  5574. if err != nil {
  5575. return nil, err
  5576. }
  5577. right, err := e.evalExprWithAggregates(ex.Right, rows)
  5578. if err != nil {
  5579. return nil, err
  5580. }
  5581. // Use the same logic as evalBinaryExpr to preserve integer semantics.
  5582. combined := &parser.BinaryExpr{Op: ex.Op}
  5583. return e.applyBinaryOp(combined.Op, left, right)
  5584. case *parser.FunctionCall:
  5585. name := strings.ToUpper(ex.Name)
  5586. switch name {
  5587. case "COUNT", "SUM", "AVG", "MIN", "MAX", "TOTAL", "GROUP_CONCAT",
  5588. "JSON_GROUP_ARRAY", "JSONB_GROUP_ARRAY":
  5589. return e.evalAggregateExpr(expr, rows)
  5590. default:
  5591. // Non-aggregate: evaluate each arg with aggregate context, then apply scalar.
  5592. args := make([]interface{}, len(ex.Args))
  5593. for i, arg := range ex.Args {
  5594. v, err := e.evalExprWithAggregates(arg, rows)
  5595. if err != nil {
  5596. return nil, err
  5597. }
  5598. args[i] = v
  5599. }
  5600. return e.evalBuiltinFunction(name, args)
  5601. }
  5602. case *parser.ParenExpr:
  5603. return e.evalExprWithAggregates(ex.Expr, rows)
  5604. case *parser.UnaryExpr:
  5605. operand, err := e.evalExprWithAggregates(ex.Operand, rows)
  5606. if err != nil {
  5607. return nil, err
  5608. }
  5609. switch ex.Op {
  5610. case lexer.TokenPlus:
  5611. return operand, nil
  5612. case lexer.TokenMinus:
  5613. if operand == nil {
  5614. return nil, nil
  5615. }
  5616. if isIntVal(operand) {
  5617. return -toInt64(operand), nil
  5618. }
  5619. return -toFloat(operand), nil
  5620. case lexer.TokenNOT:
  5621. if operand == nil {
  5622. return nil, nil // NOT NULL = NULL
  5623. }
  5624. return !toBool(operand), nil
  5625. default:
  5626. return nil, fmt.Errorf("unsupported unary operator: %v", ex.Op)
  5627. }
  5628. case *parser.CastExpr:
  5629. // Evaluate inner expression with aggregate context, then apply cast.
  5630. val, err := e.evalExprWithAggregates(ex.Expr, rows)
  5631. if err != nil {
  5632. return nil, err
  5633. }
  5634. if val == nil {
  5635. return nil, nil
  5636. }
  5637. switch strings.ToUpper(ex.Type.Name) {
  5638. case "INTEGER", "INT", "BIGINT", "SMALLINT", "TINYINT", "SIGNED":
  5639. if isIntVal(val) {
  5640. return toInt64(val), nil
  5641. }
  5642. return int64(toFloat(val)), nil
  5643. case "REAL", "FLOAT", "DOUBLE", "NUMERIC", "DECIMAL":
  5644. return toFloat(val), nil
  5645. case "TEXT", "VARCHAR", "CHAR", "STRING":
  5646. return fmt.Sprintf("%v", val), nil
  5647. }
  5648. return val, nil
  5649. case *parser.CaseExpr:
  5650. var operand interface{}
  5651. if ex.Operand != nil {
  5652. operand, _ = e.evalExprWithAggregates(ex.Operand, rows)
  5653. }
  5654. for _, when := range ex.Whens {
  5655. condVal, _ := e.evalExprWithAggregates(when.Condition, rows)
  5656. var matched bool
  5657. if ex.Operand != nil {
  5658. matched = operand != nil && condVal != nil && compare(operand, condVal) == 0
  5659. } else {
  5660. matched = toBool(condVal)
  5661. }
  5662. if matched {
  5663. return e.evalExprWithAggregates(when.Result, rows)
  5664. }
  5665. }
  5666. if ex.Else != nil {
  5667. return e.evalExprWithAggregates(ex.Else, rows)
  5668. }
  5669. return nil, nil
  5670. case *parser.IsNullExpr:
  5671. val, err := e.evalExprWithAggregates(ex.Left, rows)
  5672. if err != nil {
  5673. return nil, err
  5674. }
  5675. isNull := val == nil
  5676. if ex.Not {
  5677. return !isNull, nil
  5678. }
  5679. return isNull, nil
  5680. case *parser.IsDistinctExpr:
  5681. left, err := e.evalExprWithAggregates(ex.Left, rows)
  5682. if err != nil {
  5683. return nil, err
  5684. }
  5685. right, err := e.evalExprWithAggregates(ex.Right, rows)
  5686. if err != nil {
  5687. return nil, err
  5688. }
  5689. distinct := false
  5690. switch {
  5691. case left == nil && right == nil:
  5692. distinct = false
  5693. case left == nil || right == nil:
  5694. distinct = true
  5695. default:
  5696. distinct = compare(left, right) != 0
  5697. }
  5698. if ex.Not {
  5699. return !distinct, nil
  5700. }
  5701. return distinct, nil
  5702. case *parser.BetweenExpr:
  5703. val, err := e.evalExprWithAggregates(ex.Left, rows)
  5704. if err != nil {
  5705. return nil, err
  5706. }
  5707. low, err := e.evalExprWithAggregates(ex.Low, rows)
  5708. if err != nil {
  5709. return nil, err
  5710. }
  5711. high, err := e.evalExprWithAggregates(ex.High, rows)
  5712. if err != nil {
  5713. return nil, err
  5714. }
  5715. if ex.Not {
  5716. // NOT BETWEEN: val < low OR val > high
  5717. var lessThan, greaterThan interface{}
  5718. if val == nil || low == nil {
  5719. lessThan = nil
  5720. } else {
  5721. lessThan = compare(val, low) < 0
  5722. }
  5723. if val == nil || high == nil {
  5724. greaterThan = nil
  5725. } else {
  5726. greaterThan = compare(val, high) > 0
  5727. }
  5728. // Three-valued OR
  5729. if toBool(lessThan) || toBool(greaterThan) {
  5730. return true, nil
  5731. }
  5732. if lessThan == nil || greaterThan == nil {
  5733. return nil, nil
  5734. }
  5735. return false, nil
  5736. } else {
  5737. // BETWEEN: val >= low AND val <= high
  5738. if val == nil {
  5739. return nil, nil
  5740. }
  5741. if low == nil {
  5742. if high != nil && compare(val, high) > 0 {
  5743. return false, nil
  5744. }
  5745. return nil, nil
  5746. }
  5747. if compare(val, low) < 0 {
  5748. return false, nil
  5749. }
  5750. if high == nil {
  5751. return nil, nil
  5752. }
  5753. return compare(val, high) <= 0, nil
  5754. }
  5755. case *parser.InExpr:
  5756. left, err := e.evalExprWithAggregates(ex.Left, rows)
  5757. if err != nil {
  5758. return nil, err
  5759. }
  5760. // Handle subquery
  5761. if ex.Subquery != nil {
  5762. var result *Result
  5763. var err error
  5764. if e.subqueryCache != nil && e.outerRow == nil {
  5765. if cached, ok := e.subqueryCache[ex.Subquery]; ok {
  5766. result = cached
  5767. } else {
  5768. result, err = e.executeSelect(ex.Subquery)
  5769. if err == nil {
  5770. e.subqueryCache[ex.Subquery] = result
  5771. }
  5772. }
  5773. } else {
  5774. result, err = e.executeSelect(ex.Subquery)
  5775. }
  5776. if err != nil {
  5777. return nil, fmt.Errorf("IN subquery error: %w", err)
  5778. }
  5779. if len(result.Columns) != 1 {
  5780. return nil, fmt.Errorf("subquery in IN must return exactly one column")
  5781. }
  5782. if left == nil {
  5783. return nil, nil
  5784. }
  5785. sawNull := false
  5786. for _, resultRow := range result.Rows {
  5787. if len(resultRow) == 0 {
  5788. continue
  5789. }
  5790. v := resultRow[0]
  5791. if v == nil {
  5792. sawNull = true
  5793. continue
  5794. }
  5795. if compare(left, v) == 0 {
  5796. if ex.Not {
  5797. return false, nil
  5798. }
  5799. return true, nil
  5800. }
  5801. }
  5802. if sawNull {
  5803. return nil, nil
  5804. }
  5805. if ex.Not {
  5806. return true, nil
  5807. }
  5808. return false, nil
  5809. }
  5810. // Handle value list
  5811. if len(ex.Values) == 0 {
  5812. return ex.Not, nil
  5813. }
  5814. if left == nil {
  5815. return nil, nil
  5816. }
  5817. sawNull := false
  5818. for _, val := range ex.Values {
  5819. v, err := e.evalExprWithAggregates(val, rows)
  5820. if err != nil {
  5821. return nil, err
  5822. }
  5823. if v == nil {
  5824. sawNull = true
  5825. continue
  5826. }
  5827. if compare(left, v) == 0 {
  5828. if ex.Not {
  5829. return false, nil
  5830. }
  5831. return true, nil
  5832. }
  5833. }
  5834. if sawNull {
  5835. return nil, nil
  5836. }
  5837. if ex.Not {
  5838. return true, nil
  5839. }
  5840. return false, nil
  5841. default:
  5842. // Literals and non-aggregate expressions.
  5843. if len(rows) > 0 {
  5844. return e.evalExpr(expr, rows[0])
  5845. }
  5846. return e.evalExpr(expr, storage.Row{})
  5847. }
  5848. }
  5849. // Helper functions
  5850. func (e *Executor) getSelectColumns(stmt *parser.SelectStmt, schema *storage.Schema) []string {
  5851. var columns []string
  5852. for _, col := range stmt.Columns {
  5853. if col.Star {
  5854. for _, c := range schema.Columns {
  5855. columns = append(columns, c.Name)
  5856. }
  5857. } else if col.Alias != "" {
  5858. columns = append(columns, col.Alias)
  5859. } else if ref, ok := col.Expr.(*parser.ColumnRef); ok {
  5860. columns = append(columns, ref.Column)
  5861. } else {
  5862. columns = append(columns, fmt.Sprintf("column%d", len(columns)+1))
  5863. }
  5864. }
  5865. return columns
  5866. }
  5867. func (e *Executor) hasAggregates(columns []parser.SelectColumn) bool {
  5868. for _, col := range columns {
  5869. if e.isAggregate(col.Expr) {
  5870. return true
  5871. }
  5872. }
  5873. return false
  5874. }
  5875. func (e *Executor) isAggregate(expr parser.Expr) bool {
  5876. if _, ok := expr.(*parser.WindowExpr); ok {
  5877. // Window functions are computed after grouping; they are not aggregates.
  5878. return false
  5879. }
  5880. if fn, ok := expr.(*parser.FunctionCall); ok {
  5881. name := strings.ToUpper(fn.Name)
  5882. switch name {
  5883. case "COUNT", "SUM", "AVG", "MIN", "MAX", "TOTAL", "GROUP_CONCAT",
  5884. "JSON_GROUP_ARRAY", "JSONB_GROUP_ARRAY":
  5885. return true
  5886. }
  5887. // Non-aggregate function: check if any arg contains an aggregate.
  5888. for _, arg := range fn.Args {
  5889. if e.isAggregate(arg) {
  5890. return true
  5891. }
  5892. }
  5893. return false
  5894. }
  5895. switch ex := expr.(type) {
  5896. case *parser.UnaryExpr:
  5897. return e.isAggregate(ex.Operand)
  5898. case *parser.BinaryExpr:
  5899. return e.isAggregate(ex.Left) || e.isAggregate(ex.Right)
  5900. case *parser.ParenExpr:
  5901. return e.isAggregate(ex.Expr)
  5902. case *parser.CaseExpr:
  5903. if ex.Operand != nil && e.isAggregate(ex.Operand) {
  5904. return true
  5905. }
  5906. for _, w := range ex.Whens {
  5907. if e.isAggregate(w.Condition) || e.isAggregate(w.Result) {
  5908. return true
  5909. }
  5910. }
  5911. if ex.Else != nil {
  5912. return e.isAggregate(ex.Else)
  5913. }
  5914. case *parser.CastExpr:
  5915. return e.isAggregate(ex.Expr)
  5916. case *parser.IsNullExpr:
  5917. return e.isAggregate(ex.Left)
  5918. case *parser.IsDistinctExpr:
  5919. return e.isAggregate(ex.Left) || e.isAggregate(ex.Right)
  5920. case *parser.BetweenExpr:
  5921. return e.isAggregate(ex.Left) || e.isAggregate(ex.Low) || e.isAggregate(ex.High)
  5922. case *parser.InExpr:
  5923. if e.isAggregate(ex.Left) {
  5924. return true
  5925. }
  5926. for _, val := range ex.Values {
  5927. if e.isAggregate(val) {
  5928. return true
  5929. }
  5930. }
  5931. return false
  5932. }
  5933. return false
  5934. }
  5935. // resolveGroupByAliases replaces GROUP BY references that name a SELECT alias
  5936. // with the aliased expression. SQLite allows `GROUP BY alias`, so grouping must
  5937. // use the same expression the projection evaluates.
  5938. func (e *Executor) resolveGroupByAliases(groupBy []parser.Expr, selectCols []parser.SelectColumn) []parser.Expr {
  5939. if len(groupBy) == 0 {
  5940. return groupBy
  5941. }
  5942. aliases := make(map[string]parser.Expr, len(selectCols))
  5943. for _, col := range selectCols {
  5944. if col.Alias != "" && col.Expr != nil {
  5945. aliases[strings.ToUpper(col.Alias)] = col.Expr
  5946. }
  5947. }
  5948. if len(aliases) == 0 {
  5949. return groupBy
  5950. }
  5951. out := make([]parser.Expr, len(groupBy))
  5952. for i, expr := range groupBy {
  5953. if ref, ok := expr.(*parser.ColumnRef); ok {
  5954. if target, ok := aliases[strings.ToUpper(ref.Column)]; ok {
  5955. out[i] = target
  5956. continue
  5957. }
  5958. }
  5959. out[i] = expr
  5960. }
  5961. return out
  5962. }
  5963. func (e *Executor) buildGroupKey(groupBy []parser.Expr, row storage.Row) string {
  5964. var parts []string
  5965. for _, expr := range groupBy {
  5966. val, _ := e.evalExpr(expr, row)
  5967. parts = append(parts, fmt.Sprintf("%v", val))
  5968. }
  5969. return strings.Join(parts, "|")
  5970. }
  5971. // resolveOrderByPositions replaces positional ORDER BY expressions (e.g. ORDER BY 1)
  5972. // with the corresponding SELECT column expressions per SQL-92 semantics.
  5973. func resolveOrderByPositions(orderBy []parser.OrderByItem, selectCols []parser.SelectColumn) []parser.OrderByItem {
  5974. result := make([]parser.OrderByItem, len(orderBy))
  5975. for i, item := range orderBy {
  5976. if lit, ok := item.Expr.(*parser.LiteralExpr); ok {
  5977. if pos, err := strconv.Atoi(lit.Value); err == nil && pos >= 1 && pos <= len(selectCols) {
  5978. col := selectCols[pos-1]
  5979. if col.Expr != nil {
  5980. result[i] = parser.OrderByItem{Expr: col.Expr, Desc: item.Desc, NullsOrder: item.NullsOrder}
  5981. continue
  5982. }
  5983. }
  5984. }
  5985. result[i] = item
  5986. }
  5987. return result
  5988. }
  5989. // orderByLess reports whether key slice a sorts before b under orderBy.
  5990. // Keys are precomputed per-row ORDER BY expression values, one per item.
  5991. func orderByLess(a, b []interface{}, orderBy []parser.OrderByItem) bool {
  5992. for i, item := range orderBy {
  5993. av, bv := a[i], b[i]
  5994. if av == nil || bv == nil {
  5995. if av == nil && bv == nil {
  5996. continue
  5997. }
  5998. // SQLite treats NULL as smaller than any value, so the default puts
  5999. // NULLs first for ASC and last for DESC. NULLS FIRST/LAST overrides it.
  6000. nullsFirst := !item.Desc
  6001. switch item.NullsOrder {
  6002. case parser.NullsFirst:
  6003. nullsFirst = true
  6004. case parser.NullsLast:
  6005. nullsFirst = false
  6006. }
  6007. if av == nil {
  6008. return nullsFirst
  6009. }
  6010. return !nullsFirst
  6011. }
  6012. cmp := compare(av, bv)
  6013. if cmp != 0 {
  6014. if item.Desc {
  6015. return cmp > 0
  6016. }
  6017. return cmp < 0
  6018. }
  6019. }
  6020. return false
  6021. }
  6022. // sortKeyOrder returns a permutation of [0..len(keys)) that sorts the keys
  6023. // ascending per orderBy.
  6024. func sortKeyOrder(keys [][]interface{}, orderBy []parser.OrderByItem) []int {
  6025. order := make([]int, len(keys))
  6026. for i := range order {
  6027. order[i] = i
  6028. }
  6029. sort.Slice(order, func(a, b int) bool {
  6030. return orderByLess(keys[order[a]], keys[order[b]], orderBy)
  6031. })
  6032. return order
  6033. }
  6034. // topNHeap is a bounded max-heap that keeps the k smallest elements (per
  6035. // orderByLess) seen so far.
  6036. type topNHeap struct {
  6037. keys [][]interface{}
  6038. idx []int
  6039. orderBy []parser.OrderByItem
  6040. }
  6041. func (h *topNHeap) Len() int { return len(h.idx) }
  6042. func (h *topNHeap) Less(i, j int) bool {
  6043. return orderByLess(h.keys[h.idx[j]], h.keys[h.idx[i]], h.orderBy)
  6044. }
  6045. func (h *topNHeap) Swap(i, j int) { h.idx[i], h.idx[j] = h.idx[j], h.idx[i] }
  6046. func (h *topNHeap) Push(x interface{}) { h.idx = append(h.idx, x.(int)) }
  6047. func (h *topNHeap) Pop() interface{} {
  6048. n := len(h.idx)
  6049. x := h.idx[n-1]
  6050. h.idx = h.idx[:n-1]
  6051. return x
  6052. }
  6053. // topNKeyOrder returns the indices of the k smallest keys (per orderByLess) in
  6054. // ascending order, without fully sorting all n elements. If k >= n it falls
  6055. // back to a full sort.
  6056. func topNKeyOrder(keys [][]interface{}, orderBy []parser.OrderByItem, k int) []int {
  6057. if k <= 0 {
  6058. return nil
  6059. }
  6060. if k >= len(keys) {
  6061. return sortKeyOrder(keys, orderBy)
  6062. }
  6063. h := &topNHeap{keys: keys, orderBy: orderBy, idx: make([]int, 0, k)}
  6064. for i := range keys {
  6065. if h.Len() < k {
  6066. heap.Push(h, i)
  6067. } else if orderByLess(keys[i], keys[h.idx[0]], orderBy) {
  6068. h.idx[0] = i
  6069. heap.Fix(h, 0)
  6070. }
  6071. }
  6072. selected := append([]int(nil), h.idx...)
  6073. sort.Slice(selected, func(a, b int) bool {
  6074. return orderByLess(keys[selected[a]], keys[selected[b]], orderBy)
  6075. })
  6076. return selected
  6077. }
  6078. func reorderRows(rows []storage.Row, order []int) {
  6079. tmp := make([]storage.Row, len(rows))
  6080. for i, idx := range order {
  6081. tmp[i] = rows[idx]
  6082. }
  6083. copy(rows, tmp)
  6084. }
  6085. // sortRowKeys precomputes the ORDER BY expression value for each row so each
  6086. // expression is evaluated once per row instead of O(n log n) times.
  6087. func (e *Executor) sortRowKeys(rows []storage.Row, orderBy []parser.OrderByItem) [][]interface{} {
  6088. keys := make([][]interface{}, len(rows))
  6089. for i, row := range rows {
  6090. ks := make([]interface{}, len(orderBy))
  6091. for j, item := range orderBy {
  6092. ks[j], _ = e.evalExpr(item.Expr, row)
  6093. }
  6094. keys[i] = ks
  6095. }
  6096. return keys
  6097. }
  6098. func (e *Executor) sortRows(rows []storage.Row, orderBy []parser.OrderByItem) {
  6099. order := sortKeyOrder(e.sortRowKeys(rows, orderBy), orderBy)
  6100. reorderRows(rows, order)
  6101. }
  6102. // topNRows sorts only enough to keep the k smallest rows (per orderBy).
  6103. func (e *Executor) topNRows(rows []storage.Row, orderBy []parser.OrderByItem, k int) []storage.Row {
  6104. order := topNKeyOrder(e.sortRowKeys(rows, orderBy), orderBy, k)
  6105. out := make([]storage.Row, len(order))
  6106. for i, idx := range order {
  6107. out[i] = rows[idx]
  6108. }
  6109. return out
  6110. }
  6111. // orderAndLimitRows applies ORDER BY (with a bounded top-N selection when a
  6112. // LIMIT is present), then OFFSET and LIMIT, preserving SQL semantics.
  6113. func (e *Executor) orderAndLimitRows(rows []storage.Row, orderBy []parser.OrderByItem, limitExpr, offsetExpr parser.Expr, selectCols []parser.SelectColumn) []storage.Row {
  6114. orderBy = resolveOrderByPositions(orderBy, selectCols)
  6115. var offset, limit int
  6116. hasOffset := offsetExpr != nil
  6117. hasLimit := limitExpr != nil
  6118. if hasOffset {
  6119. offset = e.evalIntExpr(offsetExpr)
  6120. }
  6121. if hasLimit {
  6122. limit = e.evalIntExpr(limitExpr)
  6123. }
  6124. if len(orderBy) > 0 {
  6125. if hasLimit && limit >= 0 {
  6126. k := offset + limit
  6127. if k >= 0 && k < len(rows) {
  6128. rows = e.topNRows(rows, orderBy, k)
  6129. } else {
  6130. e.sortRows(rows, orderBy)
  6131. }
  6132. } else {
  6133. e.sortRows(rows, orderBy)
  6134. }
  6135. }
  6136. if hasOffset {
  6137. if offset < len(rows) {
  6138. rows = rows[offset:]
  6139. } else {
  6140. rows = nil
  6141. }
  6142. }
  6143. if hasLimit {
  6144. if limit < len(rows) {
  6145. rows = rows[:limit]
  6146. }
  6147. }
  6148. return rows
  6149. }
  6150. // resultRowKey evaluates a single ORDER BY item against a result row, honoring
  6151. // select-column aliases exactly like the previous sortResultRows implementation.
  6152. func (e *Executor) resultRowKey(result *Result, rowIdx int, item parser.OrderByItem, columnNames []string) interface{} {
  6153. if ref, ok := item.Expr.(*parser.ColumnRef); ok && ref.Table == "" {
  6154. for idx, name := range columnNames {
  6155. if strings.EqualFold(name, ref.Column) {
  6156. if idx < len(result.Rows[rowIdx]) {
  6157. return result.Rows[rowIdx][idx]
  6158. }
  6159. }
  6160. }
  6161. }
  6162. row := e.resultRowToStorageRow(result, rowIdx)
  6163. v, _ := e.evalExpr(item.Expr, row)
  6164. return v
  6165. }
  6166. // resultRowKeys precomputes the ORDER BY expression value for each result row.
  6167. func (e *Executor) resultRowKeys(result *Result, orderBy []parser.OrderByItem, columnNames []string) [][]interface{} {
  6168. keys := make([][]interface{}, len(result.Rows))
  6169. for i := range result.Rows {
  6170. ks := make([]interface{}, len(orderBy))
  6171. for j, item := range orderBy {
  6172. ks[j] = e.resultRowKey(result, i, item, columnNames)
  6173. }
  6174. keys[i] = ks
  6175. }
  6176. return keys
  6177. }
  6178. // sortResultRows sorts Result.Rows based on ORDER BY clauses.
  6179. // It handles column aliases by matching them against the select columns.
  6180. func (e *Executor) sortResultRows(result *Result, orderBy []parser.OrderByItem, selectColumns []parser.SelectColumn, columnNames []string) {
  6181. orderBy = resolveOrderByPositions(orderBy, selectColumns)
  6182. order := sortKeyOrder(e.resultRowKeys(result, orderBy, columnNames), orderBy)
  6183. rows := make([][]interface{}, len(order))
  6184. for i, idx := range order {
  6185. rows[i] = result.Rows[idx]
  6186. }
  6187. result.Rows = rows
  6188. }
  6189. // orderAndLimitResultRows applies ORDER BY (with bounded top-N selection when a
  6190. // LIMIT is present), then OFFSET and LIMIT, to a Result's rows.
  6191. func (e *Executor) orderAndLimitResultRows(result *Result, orderBy []parser.OrderByItem, limitExpr, offsetExpr parser.Expr, selectCols []parser.SelectColumn, columnNames []string) {
  6192. orderBy = resolveOrderByPositions(orderBy, selectCols)
  6193. var offset, limit int
  6194. hasOffset := offsetExpr != nil
  6195. hasLimit := limitExpr != nil
  6196. if hasOffset {
  6197. offset = e.evalIntExpr(offsetExpr)
  6198. }
  6199. if hasLimit {
  6200. limit = e.evalIntExpr(limitExpr)
  6201. }
  6202. if len(orderBy) > 0 {
  6203. if hasLimit && limit >= 0 {
  6204. k := offset + limit
  6205. if k >= 0 && k < len(result.Rows) {
  6206. order := topNKeyOrder(e.resultRowKeys(result, orderBy, columnNames), orderBy, k)
  6207. rows := make([][]interface{}, len(order))
  6208. for i, idx := range order {
  6209. rows[i] = result.Rows[idx]
  6210. }
  6211. result.Rows = rows
  6212. } else {
  6213. e.sortResultRows(result, orderBy, nil, columnNames)
  6214. }
  6215. } else {
  6216. e.sortResultRows(result, orderBy, nil, columnNames)
  6217. }
  6218. }
  6219. if hasOffset {
  6220. if offset < len(result.Rows) {
  6221. result.Rows = result.Rows[offset:]
  6222. } else {
  6223. result.Rows = nil
  6224. }
  6225. result.RowCount = len(result.Rows)
  6226. }
  6227. if hasLimit {
  6228. if limit < len(result.Rows) {
  6229. result.Rows = result.Rows[:limit]
  6230. }
  6231. result.RowCount = len(result.Rows)
  6232. }
  6233. }
  6234. // resultRowToStorageRow converts a Result row back to storage.Row for expression evaluation.
  6235. func (e *Executor) resultRowToStorageRow(result *Result, rowIdx int) storage.Row {
  6236. row := make(storage.Row)
  6237. for colIdx, colName := range result.Columns {
  6238. if colIdx < len(result.Rows[rowIdx]) {
  6239. row[colName] = result.Rows[rowIdx][colIdx]
  6240. }
  6241. }
  6242. return row
  6243. }
  6244. func (e *Executor) evalIntExpr(expr parser.Expr) int {
  6245. val, _ := e.evalExpr(expr, nil)
  6246. return int(toFloat(val))
  6247. }
  6248. // Type conversion helpers
  6249. func isIntVal(v interface{}) bool {
  6250. switch v.(type) {
  6251. case int64, int, bool:
  6252. return true
  6253. default:
  6254. return false
  6255. }
  6256. }
  6257. func toInt64(v interface{}) int64 {
  6258. switch val := v.(type) {
  6259. case int64:
  6260. return val
  6261. case int:
  6262. return int64(val)
  6263. case float64:
  6264. return int64(val)
  6265. case bool:
  6266. if val {
  6267. return 1
  6268. }
  6269. return 0
  6270. default:
  6271. return 0
  6272. }
  6273. }
  6274. func toFloat(v interface{}) float64 {
  6275. switch val := v.(type) {
  6276. case nil:
  6277. return 0
  6278. case int64:
  6279. return float64(val)
  6280. case int:
  6281. return float64(val)
  6282. case float64:
  6283. return val
  6284. case bool:
  6285. if val {
  6286. return 1
  6287. }
  6288. return 0
  6289. case string:
  6290. f, _ := strconv.ParseFloat(val, 64)
  6291. return f
  6292. default:
  6293. return 0
  6294. }
  6295. }
  6296. func toBool(v interface{}) bool {
  6297. switch val := v.(type) {
  6298. case nil:
  6299. return false
  6300. case bool:
  6301. return val
  6302. case int64:
  6303. return val != 0
  6304. case int:
  6305. return val != 0
  6306. case float64:
  6307. return val != 0
  6308. case string:
  6309. return val != "" && val != "0" && strings.ToLower(val) != "false"
  6310. default:
  6311. return false
  6312. }
  6313. }
  6314. func toString(v interface{}) string {
  6315. if v == nil {
  6316. return ""
  6317. }
  6318. switch t := v.(type) {
  6319. case string:
  6320. return t
  6321. case []byte:
  6322. return string(t)
  6323. case jsonText:
  6324. return string(t)
  6325. case bool:
  6326. if t {
  6327. return "1"
  6328. }
  6329. return "0"
  6330. case int:
  6331. return strconv.FormatInt(int64(t), 10)
  6332. case int64:
  6333. return strconv.FormatInt(t, 10)
  6334. case uint:
  6335. return strconv.FormatUint(uint64(t), 10)
  6336. case uint64:
  6337. return strconv.FormatUint(t, 10)
  6338. case float32:
  6339. return formatSQLiteReal(float64(t))
  6340. case float64:
  6341. return formatSQLiteReal(t)
  6342. default:
  6343. return fmt.Sprintf("%v", v)
  6344. }
  6345. }
  6346. func compare(a, b interface{}) int {
  6347. if a == nil && b == nil {
  6348. return 0
  6349. }
  6350. if a == nil {
  6351. return -1
  6352. }
  6353. if b == nil {
  6354. return 1
  6355. }
  6356. // Try numeric comparison
  6357. fa, oka := toNumeric(a)
  6358. fb, okb := toNumeric(b)
  6359. if oka && okb {
  6360. if fa < fb {
  6361. return -1
  6362. }
  6363. if fa > fb {
  6364. return 1
  6365. }
  6366. return 0
  6367. }
  6368. // String comparison
  6369. sa := toString(a)
  6370. sb := toString(b)
  6371. return strings.Compare(sa, sb)
  6372. }
  6373. func toNumeric(v interface{}) (float64, bool) {
  6374. switch val := v.(type) {
  6375. case int64:
  6376. return float64(val), true
  6377. case int:
  6378. return float64(val), true
  6379. case float64:
  6380. return val, true
  6381. case string:
  6382. f, err := strconv.ParseFloat(val, 64)
  6383. return f, err == nil
  6384. default:
  6385. return 0, false
  6386. }
  6387. }
  6388. // splitANDClauses flattens a tree of AND binary expressions into a slice of leaf conditions.
  6389. func splitANDClauses(expr parser.Expr) []parser.Expr {
  6390. if bin, ok := expr.(*parser.BinaryExpr); ok && bin.Op == lexer.TokenAND {
  6391. left := splitANDClauses(bin.Left)
  6392. right := splitANDClauses(bin.Right)
  6393. return append(left, right...)
  6394. }
  6395. return []parser.Expr{expr}
  6396. }
  6397. // collectColumnRefs returns all unqualified column names referenced in an expression.
  6398. func collectColumnRefs(expr parser.Expr) []string {
  6399. var refs []string
  6400. var hasSubquery bool
  6401. var walk func(parser.Expr)
  6402. walk = func(e parser.Expr) {
  6403. if e == nil {
  6404. return
  6405. }
  6406. switch n := e.(type) {
  6407. case *parser.ColumnRef:
  6408. refs = append(refs, n.Column)
  6409. case *parser.BinaryExpr:
  6410. walk(n.Left)
  6411. walk(n.Right)
  6412. case *parser.UnaryExpr:
  6413. walk(n.Operand)
  6414. case *parser.InExpr:
  6415. walk(n.Left)
  6416. // Check for subquery
  6417. if n.Subquery != nil {
  6418. hasSubquery = true
  6419. }
  6420. for _, v := range n.Values {
  6421. walk(v)
  6422. }
  6423. case *parser.BetweenExpr:
  6424. walk(n.Left)
  6425. walk(n.Low)
  6426. walk(n.High)
  6427. case *parser.LikeExpr:
  6428. walk(n.Left)
  6429. walk(n.Pattern)
  6430. case *parser.IsNullExpr:
  6431. walk(n.Left)
  6432. case *parser.IsDistinctExpr:
  6433. walk(n.Left)
  6434. walk(n.Right)
  6435. case *parser.CaseExpr:
  6436. walk(n.Operand)
  6437. for _, w := range n.Whens {
  6438. walk(w.Condition)
  6439. walk(w.Result)
  6440. }
  6441. walk(n.Else)
  6442. case *parser.FunctionCall:
  6443. for _, a := range n.Args {
  6444. walk(a)
  6445. }
  6446. case *parser.ParenExpr:
  6447. walk(n.Expr)
  6448. case *parser.CastExpr:
  6449. walk(n.Expr)
  6450. case *parser.SubqueryExpr:
  6451. // Subqueries may reference outer columns
  6452. hasSubquery = true
  6453. case *parser.ExistsExpr:
  6454. // EXISTS subqueries may reference outer columns
  6455. hasSubquery = true
  6456. case *parser.LiteralExpr:
  6457. // Literals have no column refs
  6458. }
  6459. }
  6460. walk(expr)
  6461. // If we have subqueries, add a sentinel value to indicate non-constant
  6462. if hasSubquery {
  6463. refs = append(refs, "__subquery__")
  6464. }
  6465. return refs
  6466. }
  6467. type tableColRef struct{ tbl, col string }
  6468. // collectTableColumnRefs returns all column references with their table qualifier (may be "").
  6469. func collectTableColumnRefs(expr parser.Expr) []tableColRef {
  6470. var refs []tableColRef
  6471. var walk func(parser.Expr)
  6472. walk = func(e parser.Expr) {
  6473. if e == nil {
  6474. return
  6475. }
  6476. switch n := e.(type) {
  6477. case *parser.ColumnRef:
  6478. refs = append(refs, tableColRef{tbl: n.Table, col: n.Column})
  6479. case *parser.BinaryExpr:
  6480. walk(n.Left)
  6481. walk(n.Right)
  6482. case *parser.UnaryExpr:
  6483. walk(n.Operand)
  6484. case *parser.InExpr:
  6485. walk(n.Left)
  6486. for _, v := range n.Values {
  6487. walk(v)
  6488. }
  6489. case *parser.BetweenExpr:
  6490. walk(n.Left)
  6491. walk(n.Low)
  6492. walk(n.High)
  6493. case *parser.LikeExpr:
  6494. walk(n.Left)
  6495. walk(n.Pattern)
  6496. case *parser.IsNullExpr:
  6497. walk(n.Left)
  6498. case *parser.IsDistinctExpr:
  6499. walk(n.Left)
  6500. walk(n.Right)
  6501. case *parser.CaseExpr:
  6502. walk(n.Operand)
  6503. for _, w := range n.Whens {
  6504. walk(w.Condition)
  6505. walk(w.Result)
  6506. }
  6507. walk(n.Else)
  6508. case *parser.FunctionCall:
  6509. for _, a := range n.Args {
  6510. walk(a)
  6511. }
  6512. }
  6513. }
  6514. walk(expr)
  6515. return refs
  6516. }
  6517. // combineAND combines a list of expressions with AND.
  6518. func combineAND(clauses []parser.Expr) parser.Expr {
  6519. if len(clauses) == 0 {
  6520. return nil
  6521. }
  6522. result := clauses[0]
  6523. for _, c := range clauses[1:] {
  6524. result = &parser.BinaryExpr{Left: result, Op: lexer.TokenAND, Right: c}
  6525. }
  6526. return result
  6527. }
  6528. // matchLike matches a string against a SQL LIKE pattern.
  6529. func matchLike(s, pattern string) bool {
  6530. // Simple implementation - convert to lowercase for case-insensitive matching
  6531. s = strings.ToLower(s)
  6532. pattern = strings.ToLower(pattern)
  6533. return matchLikeHelper(s, pattern)
  6534. }
  6535. func matchLikeHelper(s, p string) bool {
  6536. if p == "" {
  6537. return s == ""
  6538. }
  6539. if p[0] == '%' {
  6540. // % matches any sequence
  6541. for i := 0; i <= len(s); i++ {
  6542. if matchLikeHelper(s[i:], p[1:]) {
  6543. return true
  6544. }
  6545. }
  6546. return false
  6547. }
  6548. if s == "" {
  6549. return false
  6550. }
  6551. if p[0] == '_' || p[0] == s[0] {
  6552. return matchLikeHelper(s[1:], p[1:])
  6553. }
  6554. return false
  6555. }
  6556. // matchGlob matches a string against a GLOB pattern.
  6557. // GLOB uses * for any sequence and ? for single character (case-sensitive).
  6558. func matchGlob(pattern, s string) bool {
  6559. return matchGlobHelper(pattern, s)
  6560. }
  6561. func matchGlobHelper(p, s string) bool {
  6562. if p == "" {
  6563. return s == ""
  6564. }
  6565. if p[0] == '*' {
  6566. // * matches any sequence
  6567. for i := 0; i <= len(s); i++ {
  6568. if matchGlobHelper(p[1:], s[i:]) {
  6569. return true
  6570. }
  6571. }
  6572. return false
  6573. }
  6574. if s == "" {
  6575. return false
  6576. }
  6577. if p[0] == '?' || p[0] == s[0] {
  6578. return matchGlobHelper(p[1:], s[1:])
  6579. }
  6580. // Handle character classes [...]
  6581. if p[0] == '[' {
  6582. end := strings.Index(p, "]")
  6583. if end > 0 {
  6584. class := p[1:end]
  6585. match := false
  6586. negate := false
  6587. if len(class) > 0 && class[0] == '^' {
  6588. negate = true
  6589. class = class[1:]
  6590. }
  6591. for _, c := range class {
  6592. if byte(c) == s[0] {
  6593. match = true
  6594. break
  6595. }
  6596. }
  6597. if negate {
  6598. match = !match
  6599. }
  6600. if match {
  6601. return matchGlobHelper(p[end+1:], s[1:])
  6602. }
  6603. }
  6604. }
  6605. return false
  6606. }
  6607. // applyDistinct removes duplicate rows from the result
  6608. func (e *Executor) applyDistinct(rows [][]interface{}) [][]interface{} {
  6609. if len(rows) == 0 {
  6610. return rows
  6611. }
  6612. seen := make(map[string]bool)
  6613. uniqueRows := make([][]interface{}, 0)
  6614. for _, row := range rows {
  6615. // Create a key from all column values
  6616. key := ""
  6617. for i, val := range row {
  6618. if i > 0 {
  6619. key += "\x00" // Use null byte as separator
  6620. }
  6621. key += fmt.Sprintf("%v", val)
  6622. }
  6623. if !seen[key] {
  6624. seen[key] = true
  6625. uniqueRows = append(uniqueRows, row)
  6626. }
  6627. }
  6628. return uniqueRows
  6629. }