executor.go 189 KB

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