2
0

executor.go 238 KB

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