executor.go 237 KB

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