2
0

executor.go 195 KB

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