2
0

executor.go 224 KB

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