executor.go 205 KB

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