2
0

executor.go 209 KB

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