executor.go 242 KB

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