executor.go 235 KB

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