executor.go 205 KB

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