executor.go 212 KB

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