executor.go 199 KB

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