executor.go 217 KB

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