2
0

executor.go 232 KB

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