2
0

executor.go 228 KB

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