executor.go 199 KB

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