executor.go 200 KB

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