2
0

executor.go 202 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620
  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.rejectExpressionIndexRename(table, action.OldName); err != nil {
  3908. return nil, err
  3909. }
  3910. if err := e.schema.RenameColumn(table, action.OldName, action.NewName); err != nil {
  3911. return nil, err
  3912. }
  3913. // Update catalog
  3914. e.SyncCatalog()
  3915. result := NewResult("ALTER TABLE")
  3916. return result, nil
  3917. }
  3918. // rejectExpressionIndexRename refuses to rename a column that a stored index
  3919. // expression references. Expression text is persisted verbatim, so the rename
  3920. // cannot rewrite it; leaving the old identifier behind would silently unbind a
  3921. // UNIQUE expression index, because its rows no longer resolve the referenced
  3922. // column.
  3923. func (e *Executor) rejectExpressionIndexRename(table, column string) error {
  3924. indexes, err := e.schema.ListTableIndexes(table)
  3925. if err != nil {
  3926. return err
  3927. }
  3928. for _, idx := range indexes {
  3929. for _, ic := range idx.Columns {
  3930. if ic.Expression == "" {
  3931. continue
  3932. }
  3933. references, err := storedExpressionReferencesColumn(ic.Expression, column)
  3934. if err != nil {
  3935. return fmt.Errorf("index %s: %w", idx.Name, err)
  3936. }
  3937. if references {
  3938. return pgerror.Unsupported(
  3939. "cannot rename column %s: index %s depends on it through the expression %s; drop the index, rename the column, then recreate the index",
  3940. column, idx.Name, ic.Expression,
  3941. )
  3942. }
  3943. }
  3944. }
  3945. return nil
  3946. }
  3947. // Transaction execution methods
  3948. // executeBegin starts a new transaction.
  3949. func (e *Executor) executeBegin(stmt *parser.BeginStmt) (*Result, error) {
  3950. if e.inTransaction {
  3951. return nil, fmt.Errorf("cannot start a transaction within a transaction")
  3952. }
  3953. if err := e.session.Begin(); err != nil {
  3954. return nil, err
  3955. }
  3956. e.inTransaction = true
  3957. e.savepoints = nil
  3958. e.savepointPositions = nil
  3959. e.clearNotificationState()
  3960. result := NewResult("BEGIN")
  3961. return result, nil
  3962. }
  3963. // executeCommit commits the current transaction.
  3964. func (e *Executor) executeCommit(stmt *parser.CommitStmt) (*Result, error) {
  3965. if !e.inTransaction {
  3966. return nil, fmt.Errorf("cannot commit: no transaction in progress")
  3967. }
  3968. lsn, err := e.session.CommitWithLSN()
  3969. if err != nil {
  3970. e.inTransaction = false
  3971. e.savepoints = nil
  3972. e.savepointPositions = nil
  3973. e.finishRollback()
  3974. return nil, err
  3975. }
  3976. e.inTransaction = false
  3977. e.savepoints = nil
  3978. e.savepointPositions = nil
  3979. e.finishCommit(lsn)
  3980. result := NewResult("COMMIT")
  3981. result.LSN = lsn
  3982. return result, nil
  3983. }
  3984. // executeRollback rolls back the current transaction or to a savepoint.
  3985. func (e *Executor) executeRollback(stmt *parser.RollbackStmt) (*Result, error) {
  3986. if !e.inTransaction {
  3987. return nil, fmt.Errorf("cannot rollback: no transaction in progress")
  3988. }
  3989. if stmt.Savepoint != "" {
  3990. // Rollback to savepoint
  3991. return e.rollbackToSavepoint(stmt.Savepoint)
  3992. }
  3993. if err := e.session.Rollback(); err != nil {
  3994. return nil, err
  3995. }
  3996. e.inTransaction = false
  3997. e.savepoints = nil
  3998. e.savepointPositions = nil
  3999. e.finishRollback()
  4000. // total_changes() is monotonic (SQLite semantics): it is NOT decremented on
  4001. // rollback. last_insert_rowid() and changes() also intentionally hold.
  4002. result := NewResult("ROLLBACK")
  4003. return result, nil
  4004. }
  4005. // executeSavepoint creates a savepoint.
  4006. func (e *Executor) executeSavepoint(stmt *parser.SavepointStmt) (*Result, error) {
  4007. if !e.inTransaction {
  4008. // SQLite allows SAVEPOINT outside transaction (starts implicit transaction)
  4009. if err := e.session.Begin(); err != nil {
  4010. return nil, err
  4011. }
  4012. e.inTransaction = true
  4013. e.savepoints = nil
  4014. e.savepointPositions = nil
  4015. e.clearNotificationState()
  4016. }
  4017. // Add savepoint marker
  4018. e.savepoints = append(e.savepoints, stmt.Name)
  4019. e.savepointPositions = append(e.savepointPositions, e.session.Snapshot())
  4020. e.notificationSaves = append(e.notificationSaves, e.notificationSnapshot())
  4021. result := NewResult("SAVEPOINT")
  4022. return result, nil
  4023. }
  4024. // executeRelease releases a savepoint.
  4025. func (e *Executor) executeRelease(stmt *parser.ReleaseStmt) (*Result, error) {
  4026. if !e.inTransaction {
  4027. return nil, fmt.Errorf("cannot release savepoint: no transaction in progress")
  4028. }
  4029. // Find and remove the savepoint
  4030. found := false
  4031. for i := len(e.savepoints) - 1; i >= 0; i-- {
  4032. if e.savepoints[i] == stmt.Name {
  4033. e.savepoints = e.savepoints[:i]
  4034. e.savepointPositions = e.savepointPositions[:i]
  4035. if i <= len(e.notificationSaves) {
  4036. e.notificationSaves = e.notificationSaves[:i]
  4037. }
  4038. found = true
  4039. break
  4040. }
  4041. }
  4042. if !found {
  4043. return nil, fmt.Errorf("no such savepoint: %s", stmt.Name)
  4044. }
  4045. result := NewResult("RELEASE")
  4046. return result, nil
  4047. }
  4048. // executeAttach attaches a database.
  4049. func (e *Executor) executeAttach(stmt *parser.AttachStmt) (*Result, error) {
  4050. // Check if alias already exists
  4051. if _, exists := e.attachedDatabases[stmt.Alias]; exists {
  4052. return nil, fmt.Errorf("database alias already exists: %s", stmt.Alias)
  4053. }
  4054. // Reserved alias check
  4055. if strings.EqualFold(stmt.Alias, "temp") || strings.EqualFold(stmt.Alias, "temporary") {
  4056. return nil, fmt.Errorf("reserved database alias: %s", stmt.Alias)
  4057. }
  4058. // Get the pool from the main schema manager
  4059. pool := e.schema.GetPool()
  4060. // Create new schema and table managers for the attached database
  4061. // In PizzaKV, each database is just a different namespace/prefix
  4062. schema := storage.NewSchemaManager(pool, stmt.FilePath)
  4063. table := storage.NewTableManager(pool, schema, stmt.FilePath)
  4064. // Register the database connection
  4065. e.attachedDatabases[stmt.Alias] = &DatabaseConnection{
  4066. Alias: stmt.Alias,
  4067. Path: stmt.FilePath,
  4068. Schema: schema,
  4069. Table: table,
  4070. }
  4071. // Sync the catalog with the attached database's tables
  4072. tables, _ := schema.ListTables()
  4073. for _, tableName := range tables {
  4074. tSchema, err := schema.GetSchema(tableName)
  4075. if err != nil {
  4076. continue
  4077. }
  4078. // Add with database prefix
  4079. tableInfo := tSchema.ToAnalyzerTableInfo()
  4080. tableInfo.Name = stmt.Alias + "." + tableInfo.Name
  4081. e.catalog.CreateTable(tableInfo)
  4082. }
  4083. result := NewResult("ATTACH")
  4084. return result, nil
  4085. }
  4086. // executeDetach detaches a database.
  4087. func (e *Executor) executeDetach(stmt *parser.DetachStmt) (*Result, error) {
  4088. // Cannot detach main database
  4089. if strings.EqualFold(stmt.Alias, "main") {
  4090. return nil, fmt.Errorf("cannot detach main database")
  4091. }
  4092. // Check if database exists
  4093. if _, exists := e.attachedDatabases[stmt.Alias]; !exists {
  4094. return nil, fmt.Errorf("no such database: %s", stmt.Alias)
  4095. }
  4096. // Remove from attached databases
  4097. delete(e.attachedDatabases, stmt.Alias)
  4098. // Note: We don't remove from catalog as that would be more complex
  4099. // In a production system, we'd need to track which tables belong to which database
  4100. result := NewResult("DETACH")
  4101. return result, nil
  4102. }
  4103. // rollbackToSavepoint rolls back to a specific savepoint.
  4104. func (e *Executor) rollbackToSavepoint(name string) (*Result, error) {
  4105. // Find savepoint index
  4106. savepointIdx := -1
  4107. for i := len(e.savepoints) - 1; i >= 0; i-- {
  4108. if e.savepoints[i] == name {
  4109. savepointIdx = i
  4110. break
  4111. }
  4112. }
  4113. if savepointIdx == -1 {
  4114. return nil, fmt.Errorf("no such savepoint: %s", name)
  4115. }
  4116. logPosition := e.savepointPositions[savepointIdx]
  4117. e.session.RollbackTo(logPosition)
  4118. if savepointIdx < len(e.notificationSaves) {
  4119. e.rollbackNotificationsTo(e.notificationSaves[savepointIdx])
  4120. e.notificationSaves = e.notificationSaves[:savepointIdx+1]
  4121. }
  4122. // Remove savepoints after the target
  4123. e.savepoints = e.savepoints[:savepointIdx+1]
  4124. e.savepointPositions = e.savepointPositions[:savepointIdx+1]
  4125. result := NewResult("ROLLBACK")
  4126. return result, nil
  4127. }
  4128. // RollbackActive rolls back an open transaction, such as when its client
  4129. // disconnects before sending COMMIT or ROLLBACK.
  4130. func (e *Executor) RollbackActive() error {
  4131. if !e.inTransaction {
  4132. return nil
  4133. }
  4134. _, err := e.executeRollback(&parser.RollbackStmt{})
  4135. return err
  4136. }
  4137. // extractIndexableCondition extracts column name and value from a simple equality condition.
  4138. // Returns (column, value, true) if the expression is column = literal.
  4139. func (e *Executor) extractIndexableCondition(expr parser.Expr) (string, interface{}, bool) {
  4140. binExpr, ok := expr.(*parser.BinaryExpr)
  4141. if !ok {
  4142. return "", nil, false
  4143. }
  4144. // Only handle equality for now
  4145. if binExpr.Op != lexer.TokenEq {
  4146. return "", nil, false
  4147. }
  4148. // Check for column = literal pattern
  4149. colRef, leftIsCol := binExpr.Left.(*parser.ColumnRef)
  4150. litExpr, rightIsLit := binExpr.Right.(*parser.LiteralExpr)
  4151. if leftIsCol && rightIsLit && colRef.Table == "" {
  4152. val, _ := e.evalLiteral(litExpr)
  4153. return colRef.Column, val, true
  4154. }
  4155. // Check for literal = column pattern
  4156. litExpr, leftIsLit := binExpr.Left.(*parser.LiteralExpr)
  4157. colRef, rightIsCol := binExpr.Right.(*parser.ColumnRef)
  4158. if leftIsLit && rightIsCol && colRef.Table == "" {
  4159. val, _ := e.evalLiteral(litExpr)
  4160. return colRef.Column, val, true
  4161. }
  4162. return "", nil, false
  4163. }
  4164. // Bound only simple scans. Final OFFSET/LIMIT is still applied once by the
  4165. // normal result path; transactions conservatively retain their full read set.
  4166. func scanLimit(stmt *parser.SelectStmt) (int, bool) {
  4167. if stmt.Limit == nil || len(stmt.From) != 1 || stmt.From[0].Join != nil ||
  4168. stmt.From[0].Alias != "" || stmt.Distinct || len(stmt.GroupBy) != 0 ||
  4169. stmt.Having != nil || len(stmt.OrderBy) != 0 || stmt.Compound != nil || len(stmt.With) != 0 {
  4170. return 0, false
  4171. }
  4172. for _, column := range stmt.Columns {
  4173. switch column.Expr.(type) {
  4174. case *parser.ColumnRef, *parser.LiteralExpr:
  4175. default:
  4176. if !column.Star {
  4177. return 0, false
  4178. }
  4179. }
  4180. }
  4181. literalInt := func(expr parser.Expr) (int, bool) {
  4182. literal, ok := expr.(*parser.LiteralExpr)
  4183. if !ok || literal.Type != lexer.TokenNumber {
  4184. return 0, false
  4185. }
  4186. n, err := strconv.Atoi(literal.Value)
  4187. return n, err == nil && n >= 0
  4188. }
  4189. limit, ok := literalInt(stmt.Limit)
  4190. if !ok {
  4191. return 0, false
  4192. }
  4193. if limit == 0 {
  4194. return 0, true
  4195. }
  4196. if stmt.Offset != nil {
  4197. offset, valid := literalInt(stmt.Offset)
  4198. if !valid || offset > int(^uint(0)>>1)-limit {
  4199. return 0, false
  4200. }
  4201. limit += offset
  4202. }
  4203. return limit, true
  4204. }
  4205. func (e *Executor) extractSelectLookupCondition(expr parser.Expr, table parser.TableRef) (string, interface{}, bool) {
  4206. for join := table.Join; join != nil; join = join.Table.Join {
  4207. if join.Type == parser.JoinRight || join.Type == parser.JoinFull {
  4208. return "", nil, false
  4209. }
  4210. }
  4211. bin, ok := expr.(*parser.BinaryExpr)
  4212. if !ok {
  4213. return "", nil, false
  4214. }
  4215. copyExpr := *bin
  4216. for _, side := range []*parser.Expr{&copyExpr.Left, &copyExpr.Right} {
  4217. if column, ok := (*side).(*parser.ColumnRef); ok {
  4218. if column.Table == "" && table.Join != nil {
  4219. return "", nil, false
  4220. }
  4221. qualifier := table.Alias
  4222. if qualifier == "" {
  4223. qualifier = table.Name
  4224. }
  4225. if column.Table != "" && !strings.EqualFold(column.Table, qualifier) {
  4226. return "", nil, false
  4227. }
  4228. copyColumn := *column
  4229. copyColumn.Table = ""
  4230. *side = &copyColumn
  4231. }
  4232. }
  4233. return e.extractIndexableCondition(&copyExpr)
  4234. }
  4235. // Numeric strings can compare equal to differently formatted primary keys;
  4236. // a direct durable-key lookup would miss them. Keep those comparisons on the
  4237. // scan path until primary-key affinity has a canonical storage representation.
  4238. func safePrimaryKeyLiteral(value interface{}) bool {
  4239. if value == nil {
  4240. return false
  4241. }
  4242. if text, ok := value.(string); ok {
  4243. _, numeric := toNumeric(text)
  4244. return !numeric
  4245. }
  4246. return true
  4247. }
  4248. // executePragma executes a PRAGMA statement.
  4249. func (e *Executor) executePragma(stmt *parser.PragmaStmt) (*Result, error) {
  4250. switch stmt.Name {
  4251. case "table_info":
  4252. return e.pragmaTableInfo(stmt.Arg)
  4253. case "table_list":
  4254. return e.pragmaTableList()
  4255. case "database_list":
  4256. return e.pragmaDatabaseList()
  4257. case "version":
  4258. return e.pragmaVersion()
  4259. case "foreign_keys":
  4260. result := NewResult("PRAGMA")
  4261. if stmt.Value == nil {
  4262. result.AddColumn("foreign_keys")
  4263. result.AddRow(int64(0))
  4264. return result, nil
  4265. }
  4266. if ref, ok := stmt.Value.(*parser.ColumnRef); ok && strings.EqualFold(ref.Column, "off") {
  4267. return result, nil
  4268. }
  4269. if literal, ok := stmt.Value.(*parser.LiteralExpr); ok && literal.Value == "0" {
  4270. return result, nil
  4271. }
  4272. return nil, fmt.Errorf("PizzaSQL does not enforce foreign keys; only PRAGMA foreign_keys = OFF is supported")
  4273. default:
  4274. return nil, fmt.Errorf("unknown pragma: %s", stmt.Name)
  4275. }
  4276. }
  4277. // pragmaTableInfo returns column information for a table.
  4278. func (e *Executor) pragmaTableInfo(tableName string) (*Result, error) {
  4279. if tableName == "" {
  4280. return nil, fmt.Errorf("table_info requires a table name")
  4281. }
  4282. schema, err := e.schema.GetSchema(tableName)
  4283. if err != nil {
  4284. return nil, err
  4285. }
  4286. result := NewResult("PRAGMA")
  4287. result.AddColumn("cid")
  4288. result.AddColumn("name")
  4289. result.AddColumn("type")
  4290. result.AddColumn("notnull")
  4291. result.AddColumn("dflt_value")
  4292. result.AddColumn("pk")
  4293. for i, col := range schema.Columns {
  4294. notnull := 0
  4295. if !col.Nullable {
  4296. notnull = 1
  4297. }
  4298. pk := 0
  4299. if col.PrimaryKey {
  4300. pk = 1
  4301. }
  4302. result.AddRow(int64(i), col.Name, col.Type, int64(notnull), col.Default, int64(pk))
  4303. }
  4304. return result, nil
  4305. }
  4306. // pragmaTableList returns a list of all tables.
  4307. func (e *Executor) pragmaTableList() (*Result, error) {
  4308. tables, err := e.schema.ListTables()
  4309. if err != nil {
  4310. return nil, err
  4311. }
  4312. result := NewResult("PRAGMA")
  4313. result.AddColumn("schema")
  4314. result.AddColumn("name")
  4315. result.AddColumn("type")
  4316. for _, t := range tables {
  4317. result.AddRow("main", t, "table")
  4318. }
  4319. return result, nil
  4320. }
  4321. // pragmaDatabaseList returns a list of databases.
  4322. func (e *Executor) pragmaDatabaseList() (*Result, error) {
  4323. result := NewResult("PRAGMA")
  4324. result.AddColumn("seq")
  4325. result.AddColumn("name")
  4326. result.AddColumn("file")
  4327. // We only have one database
  4328. result.AddRow(int64(0), "main", "")
  4329. return result, nil
  4330. }
  4331. // pragmaVersion returns the PizzaSQL version.
  4332. func (e *Executor) pragmaVersion() (*Result, error) {
  4333. result := NewResult("PRAGMA")
  4334. result.AddColumn("version")
  4335. result.AddRow(version.String())
  4336. return result, nil
  4337. }
  4338. // executeExplain executes an EXPLAIN statement.
  4339. // executeAnalyze accepts ANALYZE as a documented no-op. PizzaSQL has no
  4340. // cost-based optimizer or persisted statistics, so there is nothing to gather;
  4341. // the statement exists so SQLite migrations that end with ANALYZE succeed.
  4342. func (e *Executor) executeAnalyze(stmt *parser.AnalyzeStmt) (*Result, error) {
  4343. return NewResult("ANALYZE"), nil
  4344. }
  4345. func (e *Executor) executeExplain(stmt *parser.ExplainStmt) (*Result, error) {
  4346. result := NewResult("EXPLAIN")
  4347. if stmt.QueryPlan {
  4348. // EXPLAIN QUERY PLAN format
  4349. result.AddColumn("id")
  4350. result.AddColumn("parent")
  4351. result.AddColumn("notused")
  4352. result.AddColumn("detail")
  4353. plan := e.generateQueryPlan(stmt.Statement)
  4354. for i, step := range plan {
  4355. result.AddRow(int64(i), int64(0), int64(0), step)
  4356. }
  4357. } else {
  4358. // Simple EXPLAIN format
  4359. result.AddColumn("addr")
  4360. result.AddColumn("opcode")
  4361. result.AddColumn("p1")
  4362. result.AddColumn("p2")
  4363. result.AddColumn("p3")
  4364. result.AddColumn("p4")
  4365. result.AddColumn("p5")
  4366. result.AddColumn("comment")
  4367. ops := e.generateOpcodes(stmt.Statement)
  4368. for i, op := range ops {
  4369. result.AddRow(int64(i), op, int64(0), int64(0), int64(0), "", int64(0), "")
  4370. }
  4371. }
  4372. return result, nil
  4373. }
  4374. // generateQueryPlan generates a simple query plan description.
  4375. func (e *Executor) generateQueryPlan(stmt parser.Statement) []string {
  4376. var plan []string
  4377. switch s := stmt.(type) {
  4378. case *parser.SelectStmt:
  4379. if len(s.From) > 0 {
  4380. plan = append(plan, fmt.Sprintf("SCAN TABLE %s", s.From[0].Name))
  4381. if s.Where != nil {
  4382. plan = append(plan, "FILTER")
  4383. }
  4384. if len(s.OrderBy) > 0 {
  4385. plan = append(plan, "SORT")
  4386. }
  4387. if s.Limit != nil {
  4388. plan = append(plan, "LIMIT")
  4389. }
  4390. } else {
  4391. plan = append(plan, "SCALAR EXPRESSION")
  4392. }
  4393. case *parser.InsertStmt:
  4394. plan = append(plan, fmt.Sprintf("INSERT INTO %s", s.Table.Name))
  4395. case *parser.UpdateStmt:
  4396. plan = append(plan, fmt.Sprintf("SCAN TABLE %s", s.Table.Name))
  4397. plan = append(plan, "UPDATE")
  4398. case *parser.DeleteStmt:
  4399. plan = append(plan, fmt.Sprintf("SCAN TABLE %s", s.Table.Name))
  4400. plan = append(plan, "DELETE")
  4401. default:
  4402. plan = append(plan, "EXECUTE")
  4403. }
  4404. return plan
  4405. }
  4406. // generateOpcodes generates simplified opcodes for EXPLAIN.
  4407. func (e *Executor) generateOpcodes(stmt parser.Statement) []string {
  4408. var ops []string
  4409. switch s := stmt.(type) {
  4410. case *parser.SelectStmt:
  4411. ops = append(ops, "Init")
  4412. if len(s.From) > 0 {
  4413. ops = append(ops, "OpenRead")
  4414. ops = append(ops, "Rewind")
  4415. ops = append(ops, "Column")
  4416. ops = append(ops, "ResultRow")
  4417. ops = append(ops, "Next")
  4418. ops = append(ops, "Close")
  4419. } else {
  4420. ops = append(ops, "Integer")
  4421. ops = append(ops, "ResultRow")
  4422. }
  4423. ops = append(ops, "Halt")
  4424. case *parser.InsertStmt:
  4425. ops = append(ops, "Init")
  4426. ops = append(ops, "OpenWrite")
  4427. ops = append(ops, "NewRowid")
  4428. ops = append(ops, "Insert")
  4429. ops = append(ops, "Close")
  4430. ops = append(ops, "Halt")
  4431. case *parser.UpdateStmt:
  4432. ops = append(ops, "Init")
  4433. ops = append(ops, "OpenWrite")
  4434. ops = append(ops, "Rewind")
  4435. ops = append(ops, "Column")
  4436. ops = append(ops, "Update")
  4437. ops = append(ops, "Next")
  4438. ops = append(ops, "Close")
  4439. ops = append(ops, "Halt")
  4440. case *parser.DeleteStmt:
  4441. ops = append(ops, "Init")
  4442. ops = append(ops, "OpenWrite")
  4443. ops = append(ops, "Rewind")
  4444. ops = append(ops, "Delete")
  4445. ops = append(ops, "Next")
  4446. ops = append(ops, "Close")
  4447. ops = append(ops, "Halt")
  4448. default:
  4449. ops = append(ops, "Init")
  4450. ops = append(ops, "Halt")
  4451. }
  4452. return ops
  4453. }
  4454. // evalExpr evaluates an expression.
  4455. func (e *Executor) evalExpr(expr parser.Expr, row storage.Row) (interface{}, error) {
  4456. if expr == nil {
  4457. return nil, nil
  4458. }
  4459. switch ex := expr.(type) {
  4460. case *parser.LiteralExpr:
  4461. return e.evalLiteral(ex)
  4462. case *parser.ColumnRef:
  4463. return e.evalColumnRef(ex, row)
  4464. case *parser.BinaryExpr:
  4465. return e.evalBinaryExpr(ex, row)
  4466. case *parser.UnaryExpr:
  4467. return e.evalUnaryExpr(ex, row)
  4468. case *parser.FunctionCall:
  4469. return e.evalFunctionCall(ex, row)
  4470. case *parser.ParenExpr:
  4471. return e.evalExpr(ex.Expr, row)
  4472. case *parser.CaseExpr:
  4473. return e.evalCaseExpr(ex, row)
  4474. case *parser.InExpr:
  4475. return e.evalInExpr(ex, row)
  4476. case *parser.BetweenExpr:
  4477. return e.evalBetweenExpr(ex, row)
  4478. case *parser.LikeExpr:
  4479. return e.evalLikeExpr(ex, row)
  4480. case *parser.IsNullExpr:
  4481. return e.evalIsNullExpr(ex, row)
  4482. case *parser.IsDistinctExpr:
  4483. return e.evalIsDistinctExpr(ex, row)
  4484. case *parser.CastExpr:
  4485. return e.evalCastExpr(ex, row)
  4486. case *parser.SubqueryExpr:
  4487. return e.evalSubqueryExpr(ex, row)
  4488. case *parser.ExistsExpr:
  4489. return e.evalExistsExpr(ex, row)
  4490. default:
  4491. return nil, fmt.Errorf("unsupported expression type: %T", expr)
  4492. }
  4493. }
  4494. func (e *Executor) evalLiteral(lit *parser.LiteralExpr) (interface{}, error) {
  4495. switch lit.Type {
  4496. case lexer.TokenNumber:
  4497. // Check for scientific notation (e.g., 1e+06) or decimal point
  4498. if strings.Contains(lit.Value, ".") || strings.ContainsAny(lit.Value, "eE") {
  4499. f, err := strconv.ParseFloat(lit.Value, 64)
  4500. if err != nil {
  4501. return nil, err
  4502. }
  4503. // If it's a whole number (no fractional part), return as int64
  4504. if f == float64(int64(f)) {
  4505. return int64(f), nil
  4506. }
  4507. return f, nil
  4508. }
  4509. return strconv.ParseInt(lit.Value, 10, 64)
  4510. case lexer.TokenString:
  4511. return lit.Value, nil
  4512. case lexer.TokenBlob:
  4513. // The lexer stores the decoded bytes in the literal, so a blob literal
  4514. // becomes a true []byte value.
  4515. return []byte(lit.Value), nil
  4516. case lexer.TokenNULL:
  4517. return nil, nil
  4518. case lexer.TokenTRUE:
  4519. return true, nil
  4520. case lexer.TokenFALSE:
  4521. return false, nil
  4522. default:
  4523. return lit.Value, nil
  4524. }
  4525. }
  4526. func (e *Executor) evalColumnRef(ref *parser.ColumnRef, row storage.Row) (interface{}, error) {
  4527. // SQLite date/time keywords (CURRENT_TIMESTAMP, CURRENT_DATE, CURRENT_TIME)
  4528. // are lexed as identifiers; resolve them when no real column shadows them.
  4529. if ref.Table == "" {
  4530. if _, has := lookupRowValue(row, ref.Column); !has {
  4531. if val, ok := sqliteCurrentTimeValue(ref.Column); ok {
  4532. return val, nil
  4533. }
  4534. }
  4535. }
  4536. if row == nil {
  4537. return nil, fmt.Errorf("no row context for column: %s", ref.Column)
  4538. }
  4539. // For qualified column references (table.column):
  4540. //
  4541. // Resolution order:
  4542. // 1. Exact qualified key in outer row ("t1.b" → outer)
  4543. // 2. Case-insensitive qualified in outer row
  4544. // 3. Exact qualified key in current row ("x.b" → inner alias)
  4545. // 4. Case-insensitive qualified in current row
  4546. // 5. Unqualified in outer row — only reached when qualified lookup in current
  4547. // row failed, meaning the qualifier refers to an outer table not the inner
  4548. // alias (e.g. "t1.b" in a subquery "FROM t1 AS x" resolves here).
  4549. // 6. Unqualified in current row (last resort)
  4550. if ref.Table != "" {
  4551. if e.outerRow != nil {
  4552. // Step 1-2: qualified lookup in outer row
  4553. if val, ok := e.outerRow[ref.Table+"."+ref.Column]; ok {
  4554. return val, nil
  4555. }
  4556. for k, v := range e.outerRow {
  4557. if strings.EqualFold(k, ref.Table+"."+ref.Column) {
  4558. return v, nil
  4559. }
  4560. }
  4561. }
  4562. // Step 3-4: qualified lookup in current row
  4563. if val, ok := row[ref.Table+"."+ref.Column]; ok {
  4564. return val, nil
  4565. }
  4566. for k, v := range row {
  4567. if strings.EqualFold(k, ref.Table+"."+ref.Column) {
  4568. return v, nil
  4569. }
  4570. }
  4571. // Step 5: qualified lookup failed in current row — try outer row unqualified.
  4572. // This handles correlated subqueries where the qualifier names an outer table
  4573. // (e.g. "t1.b" when the inner FROM is "t1 AS x", so current row has "x.b"
  4574. // but no "t1.b").
  4575. if e.outerRow != nil {
  4576. if val, ok := e.outerRow[ref.Column]; ok {
  4577. return val, nil
  4578. }
  4579. for k, v := range e.outerRow {
  4580. if strings.EqualFold(k, ref.Column) {
  4581. return v, nil
  4582. }
  4583. }
  4584. }
  4585. }
  4586. // Step 6: unqualified fallback in current row (handles unqualified refs and
  4587. // single-table queries like "SELECT t1.a FROM t1" where rows have plain keys).
  4588. if val, ok := row[ref.Column]; ok {
  4589. return val, nil
  4590. }
  4591. for k, v := range row {
  4592. if strings.EqualFold(k, ref.Column) {
  4593. return v, nil
  4594. }
  4595. }
  4596. // For unqualified refs with an outer row context (ref.Table == "").
  4597. if e.outerRow != nil && ref.Table == "" {
  4598. if val, ok := e.outerRow[ref.Column]; ok {
  4599. return val, nil
  4600. }
  4601. for k, v := range e.outerRow {
  4602. if strings.EqualFold(k, ref.Column) {
  4603. return v, nil
  4604. }
  4605. }
  4606. }
  4607. // Hidden rowid alias (rowid/oid/_rowid_): only used when the row carries no
  4608. // real column of that name. SQLite semantics give an explicit column named
  4609. // oid/rowid/_rowid_ precedence over the hidden rowid alias, so this fallback
  4610. // runs last.
  4611. if storage.IsRowIDColumn(ref.Column) {
  4612. if val, ok := row["_rowid_"]; ok {
  4613. return val, nil
  4614. }
  4615. }
  4616. return nil, nil // Column not found, return NULL
  4617. }
  4618. func (e *Executor) evalBinaryExpr(expr *parser.BinaryExpr, row storage.Row) (interface{}, error) {
  4619. left, err := e.evalExpr(expr.Left, row)
  4620. if err != nil {
  4621. return nil, err
  4622. }
  4623. right, err := e.evalExpr(expr.Right, row)
  4624. if err != nil {
  4625. return nil, err
  4626. }
  4627. if isBitwiseOp(expr.Op) {
  4628. if left == nil || right == nil {
  4629. return nil, nil
  4630. }
  4631. return applyBitwise(expr.Op, left, right)
  4632. }
  4633. if expr.Op == lexer.TokenArrow || expr.Op == lexer.TokenArrowText {
  4634. return jsonArrowExtract(left, right, expr.Op == lexer.TokenArrowText)
  4635. }
  4636. switch expr.Op {
  4637. case lexer.TokenPlus:
  4638. if left == nil || right == nil {
  4639. return nil, nil
  4640. }
  4641. if isIntVal(left) && isIntVal(right) {
  4642. return toInt64(left) + toInt64(right), nil
  4643. }
  4644. return toFloat(left) + toFloat(right), nil
  4645. case lexer.TokenMinus:
  4646. if left == nil || right == nil {
  4647. return nil, nil
  4648. }
  4649. if isIntVal(left) && isIntVal(right) {
  4650. return toInt64(left) - toInt64(right), nil
  4651. }
  4652. return toFloat(left) - toFloat(right), nil
  4653. case lexer.TokenStar:
  4654. if left == nil || right == nil {
  4655. return nil, nil
  4656. }
  4657. if isIntVal(left) && isIntVal(right) {
  4658. return toInt64(left) * toInt64(right), nil
  4659. }
  4660. return toFloat(left) * toFloat(right), nil
  4661. case lexer.TokenSlash:
  4662. if left == nil || right == nil {
  4663. return nil, nil
  4664. }
  4665. // Integer division when both operands are integers (truncates toward zero, matching SQLite)
  4666. if isIntVal(left) && isIntVal(right) {
  4667. ri := toInt64(right)
  4668. if ri == 0 {
  4669. return nil, nil
  4670. }
  4671. return toInt64(left) / ri, nil
  4672. }
  4673. r := toFloat(right)
  4674. if r == 0 {
  4675. return nil, nil // Division by zero returns NULL
  4676. }
  4677. return toFloat(left) / r, nil
  4678. case lexer.TokenPercent:
  4679. if left == nil || right == nil {
  4680. return nil, nil
  4681. }
  4682. if isIntVal(left) && isIntVal(right) {
  4683. ri := toInt64(right)
  4684. if ri == 0 {
  4685. return nil, nil
  4686. }
  4687. return toInt64(left) % ri, nil
  4688. }
  4689. return int64(toFloat(left)) % int64(toFloat(right)), nil
  4690. case lexer.TokenEq:
  4691. if left == nil || right == nil {
  4692. return nil, nil
  4693. }
  4694. return compare(left, right) == 0, nil
  4695. case lexer.TokenNeq:
  4696. if left == nil || right == nil {
  4697. return nil, nil
  4698. }
  4699. return compare(left, right) != 0, nil
  4700. case lexer.TokenLt:
  4701. if left == nil || right == nil {
  4702. return nil, nil
  4703. }
  4704. return compare(left, right) < 0, nil
  4705. case lexer.TokenLte:
  4706. if left == nil || right == nil {
  4707. return nil, nil
  4708. }
  4709. return compare(left, right) <= 0, nil
  4710. case lexer.TokenGt:
  4711. if left == nil || right == nil {
  4712. return nil, nil
  4713. }
  4714. return compare(left, right) > 0, nil
  4715. case lexer.TokenGte:
  4716. if left == nil || right == nil {
  4717. return nil, nil
  4718. }
  4719. return compare(left, right) >= 0, nil
  4720. case lexer.TokenAND:
  4721. // Three-value logic: FALSE AND x = FALSE; NULL AND TRUE = NULL; TRUE AND TRUE = TRUE
  4722. if left != nil && !toBool(left) {
  4723. return false, nil
  4724. }
  4725. if right != nil && !toBool(right) {
  4726. return false, nil
  4727. }
  4728. if left == nil || right == nil {
  4729. return nil, nil
  4730. }
  4731. return true, nil
  4732. case lexer.TokenOR:
  4733. // Three-value logic: TRUE OR x = TRUE; NULL OR FALSE = NULL; FALSE OR FALSE = FALSE
  4734. if left != nil && toBool(left) {
  4735. return true, nil
  4736. }
  4737. if right != nil && toBool(right) {
  4738. return true, nil
  4739. }
  4740. if left == nil || right == nil {
  4741. return nil, nil
  4742. }
  4743. return false, nil
  4744. case lexer.TokenConcat:
  4745. return toString(left) + toString(right), nil
  4746. default:
  4747. return nil, fmt.Errorf("unsupported operator: %v", expr.Op)
  4748. }
  4749. }
  4750. // applyBinaryOp applies a binary operator to two already-evaluated values.
  4751. func (e *Executor) applyBinaryOp(op lexer.TokenType, left, right interface{}) (interface{}, error) {
  4752. if isBitwiseOp(op) {
  4753. if left == nil || right == nil {
  4754. return nil, nil
  4755. }
  4756. return applyBitwise(op, left, right)
  4757. }
  4758. if op == lexer.TokenArrow || op == lexer.TokenArrowText {
  4759. return jsonArrowExtract(left, right, op == lexer.TokenArrowText)
  4760. }
  4761. switch op {
  4762. case lexer.TokenPlus:
  4763. if left == nil || right == nil {
  4764. return nil, nil
  4765. }
  4766. if isIntVal(left) && isIntVal(right) {
  4767. return toInt64(left) + toInt64(right), nil
  4768. }
  4769. return toFloat(left) + toFloat(right), nil
  4770. case lexer.TokenMinus:
  4771. if left == nil || right == nil {
  4772. return nil, nil
  4773. }
  4774. if isIntVal(left) && isIntVal(right) {
  4775. return toInt64(left) - toInt64(right), nil
  4776. }
  4777. return toFloat(left) - toFloat(right), nil
  4778. case lexer.TokenStar:
  4779. if left == nil || right == nil {
  4780. return nil, nil
  4781. }
  4782. if isIntVal(left) && isIntVal(right) {
  4783. return toInt64(left) * toInt64(right), nil
  4784. }
  4785. return toFloat(left) * toFloat(right), nil
  4786. case lexer.TokenSlash:
  4787. if left == nil || right == nil {
  4788. return nil, nil
  4789. }
  4790. if isIntVal(left) && isIntVal(right) {
  4791. ri := toInt64(right)
  4792. if ri == 0 {
  4793. return nil, nil
  4794. }
  4795. return toInt64(left) / ri, nil
  4796. }
  4797. r := toFloat(right)
  4798. if r == 0 {
  4799. return nil, nil
  4800. }
  4801. return toFloat(left) / r, nil
  4802. case lexer.TokenPercent:
  4803. if left == nil || right == nil {
  4804. return nil, nil
  4805. }
  4806. if isIntVal(left) && isIntVal(right) {
  4807. ri := toInt64(right)
  4808. if ri == 0 {
  4809. return nil, nil
  4810. }
  4811. return toInt64(left) % ri, nil
  4812. }
  4813. return int64(toFloat(left)) % int64(toFloat(right)), nil
  4814. case lexer.TokenEq:
  4815. if left == nil || right == nil {
  4816. return nil, nil
  4817. }
  4818. return compare(left, right) == 0, nil
  4819. case lexer.TokenNeq:
  4820. if left == nil || right == nil {
  4821. return nil, nil
  4822. }
  4823. return compare(left, right) != 0, nil
  4824. case lexer.TokenLt:
  4825. if left == nil || right == nil {
  4826. return nil, nil
  4827. }
  4828. return compare(left, right) < 0, nil
  4829. case lexer.TokenLte:
  4830. if left == nil || right == nil {
  4831. return nil, nil
  4832. }
  4833. return compare(left, right) <= 0, nil
  4834. case lexer.TokenGt:
  4835. if left == nil || right == nil {
  4836. return nil, nil
  4837. }
  4838. return compare(left, right) > 0, nil
  4839. case lexer.TokenGte:
  4840. if left == nil || right == nil {
  4841. return nil, nil
  4842. }
  4843. return compare(left, right) >= 0, nil
  4844. case lexer.TokenAND:
  4845. if left != nil && !toBool(left) {
  4846. return false, nil
  4847. }
  4848. if right != nil && !toBool(right) {
  4849. return false, nil
  4850. }
  4851. if left == nil || right == nil {
  4852. return nil, nil
  4853. }
  4854. return true, nil
  4855. case lexer.TokenOR:
  4856. if left != nil && toBool(left) {
  4857. return true, nil
  4858. }
  4859. if right != nil && toBool(right) {
  4860. return true, nil
  4861. }
  4862. if left == nil || right == nil {
  4863. return nil, nil
  4864. }
  4865. return false, nil
  4866. case lexer.TokenConcat:
  4867. return toString(left) + toString(right), nil
  4868. default:
  4869. return nil, fmt.Errorf("unsupported operator: %v", op)
  4870. }
  4871. }
  4872. // isBitwiseOp reports whether op is a SQLite bitwise operator.
  4873. func isBitwiseOp(op lexer.TokenType) bool {
  4874. switch op {
  4875. case lexer.TokenBitAnd, lexer.TokenBitOr, lexer.TokenShiftLeft, lexer.TokenShiftRight:
  4876. return true
  4877. }
  4878. return false
  4879. }
  4880. // applyBitwise applies a bitwise operator with SQLite semantics. Operands are
  4881. // coerced to integers; a negative shift reverses direction, and an
  4882. // out-of-range shift saturates.
  4883. func applyBitwise(op lexer.TokenType, left, right interface{}) (interface{}, error) {
  4884. li := toInt64(left)
  4885. ri := toInt64(right)
  4886. switch op {
  4887. case lexer.TokenBitAnd:
  4888. return li & ri, nil
  4889. case lexer.TokenBitOr:
  4890. return li | ri, nil
  4891. case lexer.TokenShiftLeft:
  4892. return bitShiftLeft(li, ri), nil
  4893. case lexer.TokenShiftRight:
  4894. return bitShiftRight(li, ri), nil
  4895. default:
  4896. return nil, fmt.Errorf("unsupported bitwise operator: %v", op)
  4897. }
  4898. }
  4899. func bitShiftLeft(v, shift int64) int64 {
  4900. if shift < 0 {
  4901. return bitShiftRight(v, -shift)
  4902. }
  4903. if shift >= 64 {
  4904. return 0
  4905. }
  4906. return v << uint(shift)
  4907. }
  4908. func bitShiftRight(v, shift int64) int64 {
  4909. if shift < 0 {
  4910. return bitShiftLeft(v, -shift)
  4911. }
  4912. if shift >= 64 {
  4913. if v < 0 {
  4914. return -1
  4915. }
  4916. return 0
  4917. }
  4918. return v >> uint(shift)
  4919. }
  4920. // evalBuiltinFunction applies a named scalar function to pre-evaluated args.
  4921. func (e *Executor) evalBuiltinFunction(name string, args []interface{}) (interface{}, error) {
  4922. switch name {
  4923. case "NULLIF":
  4924. if len(args) >= 2 && compare(args[0], args[1]) == 0 {
  4925. return nil, nil
  4926. }
  4927. if len(args) > 0 {
  4928. return args[0], nil
  4929. }
  4930. case "IFNULL", "NVL":
  4931. if len(args) >= 2 {
  4932. if args[0] == nil {
  4933. return args[1], nil
  4934. }
  4935. return args[0], nil
  4936. }
  4937. case "COALESCE":
  4938. for _, a := range args {
  4939. if a != nil {
  4940. return a, nil
  4941. }
  4942. }
  4943. return nil, nil
  4944. case "ABS":
  4945. if len(args) > 0 && args[0] != nil {
  4946. if isIntVal(args[0]) {
  4947. v := toInt64(args[0])
  4948. if v < 0 {
  4949. return -v, nil
  4950. }
  4951. return v, nil
  4952. }
  4953. v := toFloat(args[0])
  4954. if v < 0 {
  4955. return -v, nil
  4956. }
  4957. return v, nil
  4958. }
  4959. case "LENGTH":
  4960. if len(args) > 0 && args[0] != nil {
  4961. return int64(len(fmt.Sprintf("%v", args[0]))), nil
  4962. }
  4963. }
  4964. // Fall back: store pre-evaluated values in row and build column refs.
  4965. row := make(storage.Row, len(args))
  4966. fn := &parser.FunctionCall{Name: name}
  4967. for i, a := range args {
  4968. key := fmt.Sprintf("__arg%d__", i)
  4969. row[key] = a
  4970. fn.Args = append(fn.Args, &parser.ColumnRef{Column: key})
  4971. }
  4972. return e.evalFunctionCall(fn, row)
  4973. }
  4974. func (e *Executor) evalUnaryExpr(expr *parser.UnaryExpr, row storage.Row) (interface{}, error) {
  4975. val, err := e.evalExpr(expr.Operand, row)
  4976. if err != nil {
  4977. return nil, err
  4978. }
  4979. switch expr.Op {
  4980. case lexer.TokenMinus:
  4981. if val == nil {
  4982. return nil, nil
  4983. }
  4984. if isIntVal(val) {
  4985. return -toInt64(val), nil
  4986. }
  4987. return -toFloat(val), nil
  4988. case lexer.TokenPlus:
  4989. if val == nil {
  4990. return nil, nil
  4991. }
  4992. if isIntVal(val) {
  4993. return toInt64(val), nil
  4994. }
  4995. return toFloat(val), nil
  4996. case lexer.TokenNOT:
  4997. if val == nil {
  4998. return nil, nil // NOT NULL = NULL
  4999. }
  5000. return !toBool(val), nil
  5001. case lexer.TokenBitNot:
  5002. if val == nil {
  5003. return nil, nil
  5004. }
  5005. return ^toInt64(val), nil
  5006. default:
  5007. return val, nil
  5008. }
  5009. }
  5010. func (e *Executor) evalFunctionCall(fn *parser.FunctionCall, row storage.Row) (interface{}, error) {
  5011. name := strings.ToUpper(fn.Name)
  5012. // Evaluate arguments
  5013. args := make([]interface{}, len(fn.Args))
  5014. for i, arg := range fn.Args {
  5015. val, err := e.evalExpr(arg, row)
  5016. if err != nil {
  5017. return nil, err
  5018. }
  5019. args[i] = val
  5020. }
  5021. // JSON1 scalar functions are dispatched separately to keep this switch tidy.
  5022. if val, handled, err := evalJSONFunction(name, args); handled {
  5023. return val, err
  5024. }
  5025. switch name {
  5026. case "UPPER":
  5027. if len(args) > 0 {
  5028. if args[0] == nil {
  5029. return nil, nil // NULL propagation
  5030. }
  5031. return strings.ToUpper(toString(args[0])), nil
  5032. }
  5033. case "LOWER":
  5034. if len(args) > 0 {
  5035. if args[0] == nil {
  5036. return nil, nil // NULL propagation
  5037. }
  5038. return strings.ToLower(toString(args[0])), nil
  5039. }
  5040. case "LENGTH":
  5041. if len(args) > 0 {
  5042. if args[0] == nil {
  5043. return nil, nil // NULL propagation
  5044. }
  5045. return int64(len(toString(args[0]))), nil
  5046. }
  5047. case "ABS":
  5048. if len(args) > 0 {
  5049. if args[0] == nil {
  5050. return nil, nil
  5051. }
  5052. v := toFloat(args[0])
  5053. if v < 0 {
  5054. return -v, nil
  5055. }
  5056. return v, nil
  5057. }
  5058. case "COALESCE":
  5059. for _, arg := range args {
  5060. if arg != nil {
  5061. return arg, nil
  5062. }
  5063. }
  5064. return nil, nil
  5065. case "NULLIF":
  5066. if len(args) >= 2 && compare(args[0], args[1]) == 0 {
  5067. return nil, nil
  5068. }
  5069. if len(args) > 0 {
  5070. return args[0], nil
  5071. }
  5072. case "IFNULL":
  5073. if len(args) >= 2 {
  5074. if args[0] == nil {
  5075. return args[1], nil
  5076. }
  5077. return args[0], nil
  5078. }
  5079. case "TYPEOF":
  5080. if len(args) > 0 {
  5081. switch args[0].(type) {
  5082. case nil:
  5083. return "null", nil
  5084. case int64, int:
  5085. return "integer", nil
  5086. case float64:
  5087. return "real", nil
  5088. case string:
  5089. return "text", nil
  5090. case []byte:
  5091. return "blob", nil
  5092. default:
  5093. return "text", nil
  5094. }
  5095. }
  5096. case "SUBSTR", "SUBSTRING":
  5097. if len(args) >= 2 {
  5098. // SQLite substring semantics. Indices are 1-based and inclusive:
  5099. // a zero or negative Y shifts the window rather than simply
  5100. // clamping, e.g. substr('US-NY', 0, 3) is 'US', not 'US-'.
  5101. runes := []rune(toString(args[0]))
  5102. n := len(runes)
  5103. y := int(toFloat(args[1]))
  5104. var start1, end1 int
  5105. switch {
  5106. case y < 0:
  5107. start1 = n + y + 1
  5108. case y == 0:
  5109. start1 = 1
  5110. default:
  5111. start1 = y
  5112. }
  5113. if len(args) >= 3 {
  5114. z := int(toFloat(args[2]))
  5115. switch {
  5116. case z < 0:
  5117. end1 = start1 - 1
  5118. start1 = end1 + z + 1
  5119. case y < 0:
  5120. end1 = start1 + z - 1
  5121. case y == 0:
  5122. end1 = z - 1
  5123. default:
  5124. end1 = y + z - 1
  5125. }
  5126. } else {
  5127. end1 = n
  5128. }
  5129. if start1 < 1 {
  5130. start1 = 1
  5131. }
  5132. if end1 > n {
  5133. end1 = n
  5134. }
  5135. if start1 > n || start1 > end1 {
  5136. return "", nil
  5137. }
  5138. return string(runes[start1-1 : end1]), nil
  5139. }
  5140. case "TRIM":
  5141. if len(args) > 0 {
  5142. return strings.TrimSpace(toString(args[0])), nil
  5143. }
  5144. case "REPLACE":
  5145. if len(args) >= 3 {
  5146. return strings.ReplaceAll(toString(args[0]), toString(args[1]), toString(args[2])), nil
  5147. }
  5148. // Additional SQLite functions
  5149. case "PRINTF":
  5150. if len(args) > 0 {
  5151. format := toString(args[0])
  5152. fmtArgs := make([]interface{}, len(args)-1)
  5153. for i := 1; i < len(args); i++ {
  5154. fmtArgs[i-1] = args[i]
  5155. }
  5156. return fmt.Sprintf(format, fmtArgs...), nil
  5157. }
  5158. case "HEX":
  5159. if len(args) > 0 {
  5160. if args[0] == nil {
  5161. return nil, nil
  5162. }
  5163. if b, ok := args[0].([]byte); ok {
  5164. return strings.ToUpper(fmt.Sprintf("%x", b)), nil
  5165. }
  5166. return strings.ToUpper(fmt.Sprintf("%x", []byte(toString(args[0])))), nil
  5167. }
  5168. case "UNHEX":
  5169. if len(args) > 0 {
  5170. if args[0] == nil {
  5171. return nil, nil
  5172. }
  5173. s := toString(args[0])
  5174. result, err := hex.DecodeString(strings.TrimSpace(s))
  5175. if err != nil {
  5176. return nil, nil
  5177. }
  5178. return result, nil
  5179. }
  5180. case "RANDOM":
  5181. return rand.Int63(), nil
  5182. case "RANDOMBLOB":
  5183. if len(args) > 0 {
  5184. n := int(toFloat(args[0]))
  5185. if n <= 0 {
  5186. n = 1
  5187. }
  5188. if n > 1000000 {
  5189. n = 1000000
  5190. }
  5191. blob := make([]byte, n)
  5192. rand.Read(blob)
  5193. return blob, nil
  5194. }
  5195. case "ZEROBLOB":
  5196. if len(args) > 0 {
  5197. n := int(toFloat(args[0]))
  5198. if n <= 0 {
  5199. n = 1
  5200. }
  5201. if n > 1000000 {
  5202. n = 1000000
  5203. }
  5204. return make([]byte, n), nil
  5205. }
  5206. case "INSTR":
  5207. if len(args) >= 2 {
  5208. s := toString(args[0])
  5209. substr := toString(args[1])
  5210. idx := strings.Index(s, substr)
  5211. if idx < 0 {
  5212. return int64(0), nil
  5213. }
  5214. return int64(idx + 1), nil // SQL is 1-indexed
  5215. }
  5216. case "GLOB":
  5217. if len(args) >= 2 {
  5218. pattern := toString(args[0])
  5219. s := toString(args[1])
  5220. return matchGlob(pattern, s), nil
  5221. }
  5222. case "ROUND":
  5223. if len(args) > 0 {
  5224. v := toFloat(args[0])
  5225. decimals := 0
  5226. if len(args) >= 2 {
  5227. decimals = int(toFloat(args[1]))
  5228. }
  5229. mult := 1.0
  5230. for i := 0; i < decimals; i++ {
  5231. mult *= 10
  5232. }
  5233. return float64(int64(v*mult+0.5)) / mult, nil
  5234. }
  5235. case "MAX":
  5236. if len(args) > 0 {
  5237. max := args[0]
  5238. for _, arg := range args[1:] {
  5239. if compare(arg, max) > 0 {
  5240. max = arg
  5241. }
  5242. }
  5243. return max, nil
  5244. }
  5245. case "MIN":
  5246. if len(args) > 0 {
  5247. min := args[0]
  5248. for _, arg := range args[1:] {
  5249. if compare(arg, min) < 0 {
  5250. min = arg
  5251. }
  5252. }
  5253. return min, nil
  5254. }
  5255. case "CONCAT":
  5256. var result strings.Builder
  5257. for _, arg := range args {
  5258. result.WriteString(toString(arg))
  5259. }
  5260. return result.String(), nil
  5261. case "CONCAT_WS":
  5262. // PostgreSQL semantics: a NULL separator yields NULL; NULL arguments are
  5263. // skipped rather than converted to empty strings.
  5264. if len(args) == 0 || args[0] == nil {
  5265. return nil, nil
  5266. }
  5267. separator := toString(args[0])
  5268. parts := make([]string, 0, len(args)-1)
  5269. for _, arg := range args[1:] {
  5270. if arg != nil {
  5271. parts = append(parts, toString(arg))
  5272. }
  5273. }
  5274. return strings.Join(parts, separator), nil
  5275. // Date/Time functions
  5276. case "DATE":
  5277. return evalDateFunc(args)
  5278. case "TIME":
  5279. return evalTimeFunc(args)
  5280. case "DATETIME":
  5281. return evalDatetimeFunc(args)
  5282. case "JULIANDAY":
  5283. return evalJuliandayFunc(args)
  5284. case "UNIXEPOCH":
  5285. return evalUnixepochFunc(args)
  5286. case "STRFTIME":
  5287. return evalStrftimeFunc(args)
  5288. case "TIMEDIFF":
  5289. return evalTimediffFunc(args)
  5290. case "PERCENT_DIFF":
  5291. return evalPercentDiff(args)
  5292. case "PIZZASQL_VERSION":
  5293. return version.String(), nil
  5294. case "SQLITE_VERSION":
  5295. return SQLiteCompatVersion, nil
  5296. case "LAST_INSERT_ROWID":
  5297. return e.lastInsertRowID, nil
  5298. case "PG_BACKEND_PID":
  5299. return int64(e.backendPID), nil
  5300. case "CHANGES":
  5301. return e.changes, nil
  5302. case "TOTAL_CHANGES":
  5303. return e.totalChanges, nil
  5304. }
  5305. return nil, nil
  5306. }
  5307. func (e *Executor) evalCaseExpr(expr *parser.CaseExpr, row storage.Row) (interface{}, error) {
  5308. var operand interface{}
  5309. if expr.Operand != nil {
  5310. var err error
  5311. operand, err = e.evalExpr(expr.Operand, row)
  5312. if err != nil {
  5313. return nil, err
  5314. }
  5315. }
  5316. for _, when := range expr.Whens {
  5317. cond, err := e.evalExpr(when.Condition, row)
  5318. if err != nil {
  5319. return nil, err
  5320. }
  5321. var match bool
  5322. if expr.Operand != nil {
  5323. // Simple CASE: CASE operand WHEN val THEN ... — NULL operand matches nothing
  5324. if operand == nil {
  5325. continue
  5326. }
  5327. match = compare(operand, cond) == 0
  5328. } else {
  5329. // Searched CASE: CASE WHEN cond THEN ... — NULL condition is falsy
  5330. match = toBool(cond)
  5331. }
  5332. if match {
  5333. return e.evalExpr(when.Result, row)
  5334. }
  5335. }
  5336. if expr.Else != nil {
  5337. return e.evalExpr(expr.Else, row)
  5338. }
  5339. return nil, nil
  5340. }
  5341. func (e *Executor) evalInExpr(expr *parser.InExpr, row storage.Row) (interface{}, error) {
  5342. left, err := e.evalExpr(expr.Left, row)
  5343. if err != nil {
  5344. return nil, err
  5345. }
  5346. // Handle subquery: IN (SELECT ...)
  5347. if expr.Subquery != nil {
  5348. var result *Result
  5349. var err error
  5350. // Cache non-correlated subquery results for the duration of this query.
  5351. // Safe when outerRow is nil (no outer context that the subquery could reference).
  5352. if e.subqueryCache != nil && e.outerRow == nil {
  5353. if cached, ok := e.subqueryCache[expr.Subquery]; ok {
  5354. result = cached
  5355. } else {
  5356. result, err = e.executeSelect(expr.Subquery)
  5357. if err == nil {
  5358. e.subqueryCache[expr.Subquery] = result
  5359. }
  5360. }
  5361. } else {
  5362. result, err = e.executeSelect(expr.Subquery)
  5363. }
  5364. if err != nil {
  5365. return nil, fmt.Errorf("IN subquery error: %w", err)
  5366. }
  5367. if len(result.Columns) != 1 {
  5368. return nil, fmt.Errorf("subquery in IN must return exactly one column")
  5369. }
  5370. // SQL three-valued logic: if left is NULL → NULL; if any match → true; if any NULL → NULL; else false.
  5371. if left == nil {
  5372. return nil, nil
  5373. }
  5374. sawNull := false
  5375. for _, resultRow := range result.Rows {
  5376. if len(resultRow) == 0 {
  5377. continue
  5378. }
  5379. v := resultRow[0]
  5380. if v == nil {
  5381. sawNull = true
  5382. continue
  5383. }
  5384. if compare(left, v) == 0 {
  5385. if expr.Not {
  5386. return false, nil
  5387. }
  5388. return true, nil
  5389. }
  5390. }
  5391. if sawNull {
  5392. return nil, nil
  5393. }
  5394. if expr.Not {
  5395. return true, nil
  5396. }
  5397. return false, nil
  5398. }
  5399. // Handle value list: IN (1, 2, 3).
  5400. // Empty list: always FALSE (IN) / TRUE (NOT IN), even for NULL.
  5401. if len(expr.Values) == 0 {
  5402. return expr.Not, nil
  5403. }
  5404. // SQL three-valued logic: if left is NULL → NULL; if any match → true/false;
  5405. // if list contains NULL and no match → NULL.
  5406. if left == nil {
  5407. return nil, nil
  5408. }
  5409. sawNull := false
  5410. for _, val := range expr.Values {
  5411. v, err := e.evalExpr(val, row)
  5412. if err != nil {
  5413. return nil, err
  5414. }
  5415. if v == nil {
  5416. sawNull = true
  5417. continue
  5418. }
  5419. if compare(left, v) == 0 {
  5420. if expr.Not {
  5421. return false, nil
  5422. }
  5423. return true, nil
  5424. }
  5425. }
  5426. if sawNull {
  5427. return nil, nil
  5428. }
  5429. if expr.Not {
  5430. return true, nil
  5431. }
  5432. return false, nil
  5433. }
  5434. func (e *Executor) evalBetweenExpr(expr *parser.BetweenExpr, row storage.Row) (interface{}, error) {
  5435. val, err := e.evalExpr(expr.Left, row)
  5436. if err != nil {
  5437. return nil, err
  5438. }
  5439. low, err := e.evalExpr(expr.Low, row)
  5440. if err != nil {
  5441. return nil, err
  5442. }
  5443. high, err := e.evalExpr(expr.High, row)
  5444. if err != nil {
  5445. return nil, err
  5446. }
  5447. if expr.Not {
  5448. // NOT BETWEEN is equivalent to: val < low OR val > high
  5449. // We need to handle NULL using three-valued OR logic:
  5450. // NULL OR TRUE = TRUE
  5451. // NULL OR FALSE = NULL
  5452. // NULL OR NULL = NULL
  5453. var lessThan, greaterThan interface{}
  5454. if val == nil || low == nil {
  5455. lessThan = nil // NULL
  5456. } else {
  5457. lessThan = compare(val, low) < 0
  5458. }
  5459. if val == nil || high == nil {
  5460. greaterThan = nil // NULL
  5461. } else {
  5462. greaterThan = compare(val, high) > 0
  5463. }
  5464. // Implement three-valued OR
  5465. if toBool(lessThan) || toBool(greaterThan) {
  5466. return true, nil
  5467. }
  5468. if lessThan == nil || greaterThan == nil {
  5469. return nil, nil // NULL
  5470. }
  5471. return false, nil
  5472. } else {
  5473. // BETWEEN is equivalent to: val >= low AND val <= high
  5474. // Three-value logic: if val < low → FALSE (regardless of high); if val >= low and high is NULL → NULL
  5475. if val == nil {
  5476. return nil, nil
  5477. }
  5478. // x BETWEEN a AND b = (x >= a) AND (x <= b)
  5479. // NULL AND FALSE = FALSE; NULL AND TRUE = NULL
  5480. if low == nil {
  5481. // x >= NULL = NULL; check upper bound for early FALSE
  5482. if high != nil && compare(val, high) > 0 {
  5483. return false, nil // NULL AND FALSE = FALSE
  5484. }
  5485. return nil, nil // NULL AND TRUE/NULL = NULL
  5486. }
  5487. if compare(val, low) < 0 {
  5488. return false, nil // val < low → FALSE AND anything = FALSE
  5489. }
  5490. if high == nil {
  5491. return nil, nil // TRUE AND NULL = NULL
  5492. }
  5493. return compare(val, high) <= 0, nil
  5494. }
  5495. }
  5496. func (e *Executor) evalLikeExpr(expr *parser.LikeExpr, row storage.Row) (interface{}, error) {
  5497. val, err := e.evalExpr(expr.Left, row)
  5498. if err != nil {
  5499. return nil, err
  5500. }
  5501. pattern, err := e.evalExpr(expr.Pattern, row)
  5502. if err != nil {
  5503. return nil, err
  5504. }
  5505. s := toString(val)
  5506. p := toString(pattern)
  5507. // Convert SQL LIKE pattern to simple matching
  5508. // % matches any sequence, _ matches single character
  5509. matched := matchLike(s, p)
  5510. if expr.Not {
  5511. return !matched, nil
  5512. }
  5513. return matched, nil
  5514. }
  5515. func (e *Executor) evalIsNullExpr(expr *parser.IsNullExpr, row storage.Row) (interface{}, error) {
  5516. val, err := e.evalExpr(expr.Left, row)
  5517. if err != nil {
  5518. return nil, err
  5519. }
  5520. isNull := val == nil
  5521. if expr.Not {
  5522. return !isNull, nil
  5523. }
  5524. return isNull, nil
  5525. }
  5526. // evalIsDistinctExpr implements `a IS [NOT] DISTINCT FROM b`. It treats NULL as a
  5527. // comparable value: two NULLs are not distinct, and NULL is distinct from any
  5528. // non-NULL.
  5529. func (e *Executor) evalIsDistinctExpr(expr *parser.IsDistinctExpr, row storage.Row) (interface{}, error) {
  5530. left, err := e.evalExpr(expr.Left, row)
  5531. if err != nil {
  5532. return nil, err
  5533. }
  5534. right, err := e.evalExpr(expr.Right, row)
  5535. if err != nil {
  5536. return nil, err
  5537. }
  5538. distinct := false
  5539. switch {
  5540. case left == nil && right == nil:
  5541. distinct = false
  5542. case left == nil || right == nil:
  5543. distinct = true
  5544. default:
  5545. distinct = compare(left, right) != 0
  5546. }
  5547. if expr.Not {
  5548. return !distinct, nil
  5549. }
  5550. return distinct, nil
  5551. }
  5552. func (e *Executor) evalCastExpr(expr *parser.CastExpr, row storage.Row) (interface{}, error) {
  5553. val, err := e.evalExpr(expr.Expr, row)
  5554. if err != nil {
  5555. return nil, err
  5556. }
  5557. if val == nil {
  5558. return nil, nil // CAST(NULL AS any) = NULL
  5559. }
  5560. typeName := strings.ToUpper(expr.Type.Name)
  5561. switch {
  5562. case strings.Contains(typeName, "INT"):
  5563. return int64(toFloat(val)), nil
  5564. case strings.Contains(typeName, "REAL"), strings.Contains(typeName, "FLOAT"), strings.Contains(typeName, "DOUBLE"):
  5565. return toFloat(val), nil
  5566. case strings.Contains(typeName, "BLOB"):
  5567. if b, ok := val.([]byte); ok {
  5568. return b, nil
  5569. }
  5570. return []byte(toString(val)), nil
  5571. case strings.Contains(typeName, "TEXT"), strings.Contains(typeName, "CHAR"):
  5572. return toString(val), nil
  5573. default:
  5574. return val, nil
  5575. }
  5576. }
  5577. // evalSubqueryExpr executes a scalar subquery and returns its value.
  5578. // A scalar subquery must return exactly one column. It returns:
  5579. // - The single value if the subquery returns one row
  5580. // - NULL if the subquery returns no rows
  5581. // - Error if the subquery returns more than one row (for strict SQL compliance)
  5582. func (e *Executor) evalSubqueryExpr(expr *parser.SubqueryExpr, row storage.Row) (interface{}, error) {
  5583. if row != nil && e.correlatedAggCache != nil {
  5584. if val, ok, err := e.evalDecorrelatedAggSubquery(expr.Query, row); ok || err != nil {
  5585. return val, err
  5586. }
  5587. }
  5588. // Save and set outer row context for correlated subqueries
  5589. savedOuter := e.outerRow
  5590. e.outerRow = row
  5591. defer func() { e.outerRow = savedOuter }()
  5592. // Execute the subquery
  5593. result, err := e.executeSelect(expr.Query)
  5594. if err != nil {
  5595. return nil, fmt.Errorf("subquery error: %w", err)
  5596. }
  5597. // Check for empty result
  5598. if result.RowCount == 0 {
  5599. return nil, nil // Return NULL for empty subquery
  5600. }
  5601. // Check column count
  5602. if len(result.Columns) == 0 {
  5603. return nil, fmt.Errorf("subquery must return at least one column")
  5604. }
  5605. // For scalar subquery, return first column of first row
  5606. // Note: Strict SQL would error if more than one row is returned
  5607. // but we follow SQLite behavior which just returns the first value
  5608. if len(result.Rows) > 0 && len(result.Rows[0]) > 0 {
  5609. return result.Rows[0][0], nil
  5610. }
  5611. return nil, nil
  5612. }
  5613. func (e *Executor) evalDecorrelatedAggSubquery(query *parser.SelectStmt, outerRow storage.Row) (interface{}, bool, error) {
  5614. spec, ok := e.correlatedAggSpec(query)
  5615. if !ok {
  5616. return nil, false, nil
  5617. }
  5618. outerVal, err := e.evalExpr(spec.outerKey, outerRow)
  5619. if err != nil {
  5620. return nil, true, err
  5621. }
  5622. cache, exists := e.correlatedAggCache[query]
  5623. if !exists {
  5624. cache, err = e.buildCorrelatedAggCache(query, spec)
  5625. if err != nil {
  5626. return nil, true, err
  5627. }
  5628. e.correlatedAggCache[query] = cache
  5629. }
  5630. if outerVal == nil {
  5631. return cache.defaultValue, true, nil
  5632. }
  5633. if val, exists := cache.values[fmt.Sprintf("%v", outerVal)]; exists {
  5634. return val, true, nil
  5635. }
  5636. return cache.defaultValue, true, nil
  5637. }
  5638. func (e *Executor) correlatedAggSpec(query *parser.SelectStmt) (correlatedAggSpec, bool) {
  5639. if query == nil ||
  5640. query.Compound != nil ||
  5641. len(query.Columns) != 1 ||
  5642. len(query.From) == 0 ||
  5643. query.Where == nil ||
  5644. len(query.GroupBy) > 0 ||
  5645. query.Having != nil ||
  5646. query.Limit != nil ||
  5647. query.Offset != nil {
  5648. return correlatedAggSpec{}, false
  5649. }
  5650. if query.Columns[0].Star {
  5651. return correlatedAggSpec{}, false
  5652. }
  5653. agg, ok := query.Columns[0].Expr.(*parser.FunctionCall)
  5654. if !ok {
  5655. return correlatedAggSpec{}, false
  5656. }
  5657. switch strings.ToUpper(agg.Name) {
  5658. case "COUNT", "SUM", "AVG", "MIN", "MAX":
  5659. default:
  5660. return correlatedAggSpec{}, false
  5661. }
  5662. innerAliases := collectFromAliases(query.From)
  5663. bin, ok := query.Where.(*parser.BinaryExpr)
  5664. if !ok || bin.Op != lexer.TokenEq {
  5665. return correlatedAggSpec{}, false
  5666. }
  5667. leftRef, leftIsRef := bin.Left.(*parser.ColumnRef)
  5668. rightRef, rightIsRef := bin.Right.(*parser.ColumnRef)
  5669. if !leftIsRef || !rightIsRef {
  5670. return correlatedAggSpec{}, false
  5671. }
  5672. leftInner := refBelongsToAliases(leftRef, innerAliases)
  5673. rightInner := refBelongsToAliases(rightRef, innerAliases)
  5674. if leftInner == rightInner {
  5675. return correlatedAggSpec{}, false
  5676. }
  5677. if leftInner {
  5678. return correlatedAggSpec{innerKey: leftRef, outerKey: rightRef, aggExpr: agg}, true
  5679. }
  5680. return correlatedAggSpec{innerKey: rightRef, outerKey: leftRef, aggExpr: agg}, true
  5681. }
  5682. func (e *Executor) buildCorrelatedAggCache(query *parser.SelectStmt, spec correlatedAggSpec) (*correlatedAggCache, error) {
  5683. grouped := *query
  5684. grouped.Where = nil
  5685. grouped.GroupBy = []parser.Expr{spec.innerKey}
  5686. grouped.Having = nil
  5687. grouped.OrderBy = nil
  5688. grouped.Limit = nil
  5689. grouped.Offset = nil
  5690. grouped.Columns = []parser.SelectColumn{
  5691. {Expr: spec.innerKey, Alias: "__corr_key"},
  5692. {Expr: spec.aggExpr, Alias: "__corr_value"},
  5693. }
  5694. savedOuter := e.outerRow
  5695. e.outerRow = nil
  5696. result, err := e.executeSelect(&grouped)
  5697. e.outerRow = savedOuter
  5698. if err != nil {
  5699. return nil, fmt.Errorf("decorrelated aggregate subquery error: %w", err)
  5700. }
  5701. cache := &correlatedAggCache{
  5702. values: make(map[string]interface{}, len(result.Rows)),
  5703. defaultValue: correlatedAggDefault(spec.aggExpr),
  5704. }
  5705. for _, row := range result.Rows {
  5706. if len(row) < 2 || row[0] == nil {
  5707. continue
  5708. }
  5709. cache.values[fmt.Sprintf("%v", row[0])] = row[1]
  5710. }
  5711. return cache, nil
  5712. }
  5713. func correlatedAggDefault(expr parser.Expr) interface{} {
  5714. if fn, ok := expr.(*parser.FunctionCall); ok && strings.EqualFold(fn.Name, "COUNT") {
  5715. return int64(0)
  5716. }
  5717. return nil
  5718. }
  5719. func collectFromAliases(from []parser.TableRef) map[string]struct{} {
  5720. aliases := make(map[string]struct{})
  5721. var addRef func(parser.TableRef)
  5722. addRef = func(ref parser.TableRef) {
  5723. if ref.Name != "" {
  5724. aliases[strings.ToLower(ref.Name)] = struct{}{}
  5725. }
  5726. if ref.Alias != "" {
  5727. aliases[strings.ToLower(ref.Alias)] = struct{}{}
  5728. }
  5729. if ref.Join != nil && ref.Join.Table != nil {
  5730. addRef(*ref.Join.Table)
  5731. }
  5732. }
  5733. for _, ref := range from {
  5734. addRef(ref)
  5735. }
  5736. return aliases
  5737. }
  5738. func refBelongsToAliases(ref *parser.ColumnRef, aliases map[string]struct{}) bool {
  5739. if ref == nil || ref.Table == "" {
  5740. return false
  5741. }
  5742. _, ok := aliases[strings.ToLower(ref.Table)]
  5743. return ok
  5744. }
  5745. // evalExistsExpr evaluates an EXISTS expression.
  5746. // Returns true if the subquery returns at least one row, false otherwise.
  5747. func (e *Executor) evalExistsExpr(expr *parser.ExistsExpr, row storage.Row) (interface{}, error) {
  5748. // Save and set outer row context for correlated subqueries
  5749. savedOuter := e.outerRow
  5750. e.outerRow = row
  5751. defer func() { e.outerRow = savedOuter }()
  5752. // Execute the subquery
  5753. result, err := e.executeSelect(expr.Subquery)
  5754. if err != nil {
  5755. return nil, fmt.Errorf("EXISTS subquery error: %w", err)
  5756. }
  5757. // EXISTS returns true if any rows are returned
  5758. return len(result.Rows) > 0, nil
  5759. }
  5760. // evalAggregateExpr evaluates an aggregate expression over multiple rows.
  5761. func (e *Executor) evalAggregateExpr(expr parser.Expr, rows []storage.Row) (interface{}, error) {
  5762. fn, ok := expr.(*parser.FunctionCall)
  5763. if !ok {
  5764. // Not a function call - could be a binary expression with aggregates inside
  5765. // Evaluate it with the aggregate evaluation context
  5766. return e.evalExprWithAggregates(expr, rows)
  5767. }
  5768. name := strings.ToUpper(fn.Name)
  5769. switch name {
  5770. case "COUNT":
  5771. if fn.Star {
  5772. return int64(len(rows)), nil
  5773. }
  5774. if fn.Distinct {
  5775. seen := make(map[interface{}]struct{})
  5776. for _, row := range rows {
  5777. if len(fn.Args) > 0 {
  5778. val, _ := e.evalExpr(fn.Args[0], row)
  5779. if val != nil {
  5780. seen[val] = struct{}{}
  5781. }
  5782. }
  5783. }
  5784. return int64(len(seen)), nil
  5785. }
  5786. count := int64(0)
  5787. for _, row := range rows {
  5788. if len(fn.Args) > 0 {
  5789. val, _ := e.evalExpr(fn.Args[0], row)
  5790. if val != nil {
  5791. count++
  5792. }
  5793. }
  5794. }
  5795. return count, nil
  5796. case "SUM":
  5797. var sumInt int64
  5798. var sumFloat float64
  5799. allInt := true
  5800. hasValues := false
  5801. var seen map[interface{}]struct{}
  5802. if fn.Distinct {
  5803. seen = make(map[interface{}]struct{})
  5804. }
  5805. for _, row := range rows {
  5806. if len(fn.Args) > 0 {
  5807. val, _ := e.evalExpr(fn.Args[0], row)
  5808. if val != nil {
  5809. if fn.Distinct {
  5810. key := fmt.Sprintf("%v", val)
  5811. if _, exists := seen[key]; exists {
  5812. continue
  5813. }
  5814. seen[key] = struct{}{}
  5815. }
  5816. if isIntVal(val) {
  5817. sumInt += toInt64(val)
  5818. } else {
  5819. allInt = false
  5820. sumFloat += toFloat(val)
  5821. }
  5822. hasValues = true
  5823. }
  5824. }
  5825. }
  5826. if !hasValues {
  5827. return nil, nil
  5828. }
  5829. if allInt {
  5830. return sumInt, nil
  5831. }
  5832. return sumFloat + float64(sumInt), nil
  5833. case "AVG":
  5834. var sum float64
  5835. count := 0
  5836. for _, row := range rows {
  5837. if len(fn.Args) > 0 {
  5838. val, _ := e.evalExpr(fn.Args[0], row)
  5839. if val != nil {
  5840. sum += toFloat(val)
  5841. count++
  5842. }
  5843. }
  5844. }
  5845. if count == 0 {
  5846. return nil, nil
  5847. }
  5848. return sum / float64(count), nil
  5849. case "MIN":
  5850. var min interface{}
  5851. for _, row := range rows {
  5852. if len(fn.Args) > 0 {
  5853. val, _ := e.evalExpr(fn.Args[0], row)
  5854. if val != nil && (min == nil || compare(val, min) < 0) {
  5855. min = val
  5856. }
  5857. }
  5858. }
  5859. return min, nil
  5860. case "MAX":
  5861. var max interface{}
  5862. for _, row := range rows {
  5863. if len(fn.Args) > 0 {
  5864. val, _ := e.evalExpr(fn.Args[0], row)
  5865. if val != nil && (max == nil || compare(val, max) > 0) {
  5866. max = val
  5867. }
  5868. }
  5869. }
  5870. return max, nil
  5871. case "TOTAL":
  5872. var sum float64
  5873. for _, row := range rows {
  5874. if len(fn.Args) > 0 {
  5875. val, _ := e.evalExpr(fn.Args[0], row)
  5876. if val != nil {
  5877. sum += toFloat(val)
  5878. }
  5879. }
  5880. }
  5881. return sum, nil
  5882. case "STRING_AGG":
  5883. if len(fn.Args) == 0 {
  5884. return nil, fmt.Errorf("STRING_AGG requires at least one argument")
  5885. }
  5886. separator := ""
  5887. if len(fn.Args) > 1 && len(rows) > 0 {
  5888. sep, err := e.evalExpr(fn.Args[1], rows[0])
  5889. if err != nil {
  5890. return nil, err
  5891. }
  5892. if sep == nil {
  5893. return nil, nil
  5894. }
  5895. separator = toString(sep)
  5896. }
  5897. var seen map[string]struct{}
  5898. if fn.Distinct {
  5899. seen = make(map[string]struct{})
  5900. }
  5901. var parts []string
  5902. for _, row := range rows {
  5903. val, err := e.evalExpr(fn.Args[0], row)
  5904. if err != nil {
  5905. return nil, err
  5906. }
  5907. if val == nil {
  5908. continue
  5909. }
  5910. text := toString(val)
  5911. if fn.Distinct {
  5912. if _, exists := seen[text]; exists {
  5913. continue
  5914. }
  5915. seen[text] = struct{}{}
  5916. }
  5917. parts = append(parts, text)
  5918. }
  5919. if len(parts) == 0 {
  5920. return nil, nil
  5921. }
  5922. return strings.Join(parts, separator), nil
  5923. case "GROUP_CONCAT":
  5924. if len(fn.Args) == 0 {
  5925. return nil, fmt.Errorf("GROUP_CONCAT requires at least one argument")
  5926. }
  5927. var seen map[string]struct{}
  5928. if fn.Distinct {
  5929. seen = make(map[string]struct{})
  5930. }
  5931. var builder strings.Builder
  5932. count := 0
  5933. for _, row := range rows {
  5934. val, err := e.evalExpr(fn.Args[0], row)
  5935. if err != nil {
  5936. return nil, err
  5937. }
  5938. if val == nil {
  5939. continue
  5940. }
  5941. text := toString(val)
  5942. if fn.Distinct {
  5943. if _, exists := seen[text]; exists {
  5944. continue
  5945. }
  5946. seen[text] = struct{}{}
  5947. }
  5948. if count > 0 {
  5949. separator := ","
  5950. if len(fn.Args) > 1 {
  5951. sep, err := e.evalExpr(fn.Args[1], row)
  5952. if err != nil {
  5953. return nil, err
  5954. }
  5955. separator = toString(sep)
  5956. }
  5957. builder.WriteString(separator)
  5958. }
  5959. builder.WriteString(text)
  5960. count++
  5961. }
  5962. if count == 0 {
  5963. return nil, nil
  5964. }
  5965. return builder.String(), nil
  5966. case "JSON_GROUP_ARRAY", "JSONB_GROUP_ARRAY":
  5967. arr := make([]interface{}, 0, len(rows))
  5968. var seen map[string]struct{}
  5969. if fn.Distinct {
  5970. seen = make(map[string]struct{})
  5971. }
  5972. for _, row := range rows {
  5973. var val interface{}
  5974. if len(fn.Args) > 0 {
  5975. val, _ = e.evalExpr(fn.Args[0], row)
  5976. }
  5977. if fn.Distinct {
  5978. key := fmt.Sprintf("%v", val)
  5979. if _, exists := seen[key]; exists {
  5980. continue
  5981. }
  5982. seen[key] = struct{}{}
  5983. }
  5984. arr = append(arr, jsonArgToNode(val))
  5985. }
  5986. s, err := jsonEncode(arr)
  5987. if err != nil {
  5988. return nil, err
  5989. }
  5990. return jsonText(s), nil
  5991. default:
  5992. if isAggregateCallName(name) {
  5993. return nil, fmt.Errorf("unsupported aggregate function: %s", name)
  5994. }
  5995. // Non-aggregate scalar function: evaluate args through aggregate context
  5996. // (so COUNT/MIN/etc. inside NULLIF/COALESCE work correctly).
  5997. return e.evalExprWithAggregates(expr, rows)
  5998. }
  5999. }
  6000. // isAggregateCallName lists the aggregate functions handled by
  6001. // evalAggregateExpr. Keeping dispatch and evaluation on the same list prevents
  6002. // an unhandled aggregate from recursing between the aggregate and expression
  6003. // evaluators.
  6004. func isAggregateCallName(name string) bool {
  6005. switch strings.ToUpper(name) {
  6006. case "COUNT", "SUM", "AVG", "MIN", "MAX", "TOTAL", "GROUP_CONCAT", "STRING_AGG",
  6007. "JSON_GROUP_ARRAY", "JSONB_GROUP_ARRAY":
  6008. return true
  6009. default:
  6010. return false
  6011. }
  6012. }
  6013. // evalExprWithAggregates evaluates an expression that may contain aggregate functions
  6014. func (e *Executor) evalExprWithAggregates(expr parser.Expr, rows []storage.Row) (interface{}, error) {
  6015. switch ex := expr.(type) {
  6016. case *parser.BinaryExpr:
  6017. left, err := e.evalExprWithAggregates(ex.Left, rows)
  6018. if err != nil {
  6019. return nil, err
  6020. }
  6021. right, err := e.evalExprWithAggregates(ex.Right, rows)
  6022. if err != nil {
  6023. return nil, err
  6024. }
  6025. // Use the same logic as evalBinaryExpr to preserve integer semantics.
  6026. combined := &parser.BinaryExpr{Op: ex.Op}
  6027. return e.applyBinaryOp(combined.Op, left, right)
  6028. case *parser.FunctionCall:
  6029. name := strings.ToUpper(ex.Name)
  6030. if isAggregateCallName(name) {
  6031. return e.evalAggregateExpr(expr, rows)
  6032. }
  6033. // Non-aggregate: evaluate each arg with aggregate context, then apply scalar.
  6034. args := make([]interface{}, len(ex.Args))
  6035. for i, arg := range ex.Args {
  6036. v, err := e.evalExprWithAggregates(arg, rows)
  6037. if err != nil {
  6038. return nil, err
  6039. }
  6040. args[i] = v
  6041. }
  6042. return e.evalBuiltinFunction(name, args)
  6043. case *parser.ParenExpr:
  6044. return e.evalExprWithAggregates(ex.Expr, rows)
  6045. case *parser.UnaryExpr:
  6046. operand, err := e.evalExprWithAggregates(ex.Operand, rows)
  6047. if err != nil {
  6048. return nil, err
  6049. }
  6050. switch ex.Op {
  6051. case lexer.TokenPlus:
  6052. return operand, nil
  6053. case lexer.TokenMinus:
  6054. if operand == nil {
  6055. return nil, nil
  6056. }
  6057. if isIntVal(operand) {
  6058. return -toInt64(operand), nil
  6059. }
  6060. return -toFloat(operand), nil
  6061. case lexer.TokenNOT:
  6062. if operand == nil {
  6063. return nil, nil // NOT NULL = NULL
  6064. }
  6065. return !toBool(operand), nil
  6066. default:
  6067. return nil, fmt.Errorf("unsupported unary operator: %v", ex.Op)
  6068. }
  6069. case *parser.CastExpr:
  6070. // Evaluate inner expression with aggregate context, then apply cast.
  6071. val, err := e.evalExprWithAggregates(ex.Expr, rows)
  6072. if err != nil {
  6073. return nil, err
  6074. }
  6075. if val == nil {
  6076. return nil, nil
  6077. }
  6078. switch strings.ToUpper(ex.Type.Name) {
  6079. case "INTEGER", "INT", "BIGINT", "SMALLINT", "TINYINT", "SIGNED":
  6080. if isIntVal(val) {
  6081. return toInt64(val), nil
  6082. }
  6083. return int64(toFloat(val)), nil
  6084. case "REAL", "FLOAT", "DOUBLE", "NUMERIC", "DECIMAL":
  6085. return toFloat(val), nil
  6086. case "TEXT", "VARCHAR", "CHAR", "STRING":
  6087. return fmt.Sprintf("%v", val), nil
  6088. }
  6089. return val, nil
  6090. case *parser.CaseExpr:
  6091. var operand interface{}
  6092. if ex.Operand != nil {
  6093. operand, _ = e.evalExprWithAggregates(ex.Operand, rows)
  6094. }
  6095. for _, when := range ex.Whens {
  6096. condVal, _ := e.evalExprWithAggregates(when.Condition, rows)
  6097. var matched bool
  6098. if ex.Operand != nil {
  6099. matched = operand != nil && condVal != nil && compare(operand, condVal) == 0
  6100. } else {
  6101. matched = toBool(condVal)
  6102. }
  6103. if matched {
  6104. return e.evalExprWithAggregates(when.Result, rows)
  6105. }
  6106. }
  6107. if ex.Else != nil {
  6108. return e.evalExprWithAggregates(ex.Else, rows)
  6109. }
  6110. return nil, nil
  6111. case *parser.IsNullExpr:
  6112. val, err := e.evalExprWithAggregates(ex.Left, rows)
  6113. if err != nil {
  6114. return nil, err
  6115. }
  6116. isNull := val == nil
  6117. if ex.Not {
  6118. return !isNull, nil
  6119. }
  6120. return isNull, nil
  6121. case *parser.IsDistinctExpr:
  6122. left, err := e.evalExprWithAggregates(ex.Left, rows)
  6123. if err != nil {
  6124. return nil, err
  6125. }
  6126. right, err := e.evalExprWithAggregates(ex.Right, rows)
  6127. if err != nil {
  6128. return nil, err
  6129. }
  6130. distinct := false
  6131. switch {
  6132. case left == nil && right == nil:
  6133. distinct = false
  6134. case left == nil || right == nil:
  6135. distinct = true
  6136. default:
  6137. distinct = compare(left, right) != 0
  6138. }
  6139. if ex.Not {
  6140. return !distinct, nil
  6141. }
  6142. return distinct, nil
  6143. case *parser.BetweenExpr:
  6144. val, err := e.evalExprWithAggregates(ex.Left, rows)
  6145. if err != nil {
  6146. return nil, err
  6147. }
  6148. low, err := e.evalExprWithAggregates(ex.Low, rows)
  6149. if err != nil {
  6150. return nil, err
  6151. }
  6152. high, err := e.evalExprWithAggregates(ex.High, rows)
  6153. if err != nil {
  6154. return nil, err
  6155. }
  6156. if ex.Not {
  6157. // NOT BETWEEN: val < low OR val > high
  6158. var lessThan, greaterThan interface{}
  6159. if val == nil || low == nil {
  6160. lessThan = nil
  6161. } else {
  6162. lessThan = compare(val, low) < 0
  6163. }
  6164. if val == nil || high == nil {
  6165. greaterThan = nil
  6166. } else {
  6167. greaterThan = compare(val, high) > 0
  6168. }
  6169. // Three-valued OR
  6170. if toBool(lessThan) || toBool(greaterThan) {
  6171. return true, nil
  6172. }
  6173. if lessThan == nil || greaterThan == nil {
  6174. return nil, nil
  6175. }
  6176. return false, nil
  6177. } else {
  6178. // BETWEEN: val >= low AND val <= high
  6179. if val == nil {
  6180. return nil, nil
  6181. }
  6182. if low == nil {
  6183. if high != nil && compare(val, high) > 0 {
  6184. return false, nil
  6185. }
  6186. return nil, nil
  6187. }
  6188. if compare(val, low) < 0 {
  6189. return false, nil
  6190. }
  6191. if high == nil {
  6192. return nil, nil
  6193. }
  6194. return compare(val, high) <= 0, nil
  6195. }
  6196. case *parser.InExpr:
  6197. left, err := e.evalExprWithAggregates(ex.Left, rows)
  6198. if err != nil {
  6199. return nil, err
  6200. }
  6201. // Handle subquery
  6202. if ex.Subquery != nil {
  6203. var result *Result
  6204. var err error
  6205. if e.subqueryCache != nil && e.outerRow == nil {
  6206. if cached, ok := e.subqueryCache[ex.Subquery]; ok {
  6207. result = cached
  6208. } else {
  6209. result, err = e.executeSelect(ex.Subquery)
  6210. if err == nil {
  6211. e.subqueryCache[ex.Subquery] = result
  6212. }
  6213. }
  6214. } else {
  6215. result, err = e.executeSelect(ex.Subquery)
  6216. }
  6217. if err != nil {
  6218. return nil, fmt.Errorf("IN subquery error: %w", err)
  6219. }
  6220. if len(result.Columns) != 1 {
  6221. return nil, fmt.Errorf("subquery in IN must return exactly one column")
  6222. }
  6223. if left == nil {
  6224. return nil, nil
  6225. }
  6226. sawNull := false
  6227. for _, resultRow := range result.Rows {
  6228. if len(resultRow) == 0 {
  6229. continue
  6230. }
  6231. v := resultRow[0]
  6232. if v == nil {
  6233. sawNull = true
  6234. continue
  6235. }
  6236. if compare(left, v) == 0 {
  6237. if ex.Not {
  6238. return false, nil
  6239. }
  6240. return true, nil
  6241. }
  6242. }
  6243. if sawNull {
  6244. return nil, nil
  6245. }
  6246. if ex.Not {
  6247. return true, nil
  6248. }
  6249. return false, nil
  6250. }
  6251. // Handle value list
  6252. if len(ex.Values) == 0 {
  6253. return ex.Not, nil
  6254. }
  6255. if left == nil {
  6256. return nil, nil
  6257. }
  6258. sawNull := false
  6259. for _, val := range ex.Values {
  6260. v, err := e.evalExprWithAggregates(val, rows)
  6261. if err != nil {
  6262. return nil, err
  6263. }
  6264. if v == nil {
  6265. sawNull = true
  6266. continue
  6267. }
  6268. if compare(left, v) == 0 {
  6269. if ex.Not {
  6270. return false, nil
  6271. }
  6272. return true, nil
  6273. }
  6274. }
  6275. if sawNull {
  6276. return nil, nil
  6277. }
  6278. if ex.Not {
  6279. return true, nil
  6280. }
  6281. return false, nil
  6282. default:
  6283. // Literals and non-aggregate expressions.
  6284. if len(rows) > 0 {
  6285. return e.evalExpr(expr, rows[0])
  6286. }
  6287. return e.evalExpr(expr, storage.Row{})
  6288. }
  6289. }
  6290. // Helper functions
  6291. func (e *Executor) getSelectColumns(stmt *parser.SelectStmt, schema *storage.Schema) []string {
  6292. var columns []string
  6293. for _, col := range stmt.Columns {
  6294. if col.Star {
  6295. for _, c := range schema.Columns {
  6296. columns = append(columns, c.Name)
  6297. }
  6298. } else if col.Alias != "" {
  6299. columns = append(columns, col.Alias)
  6300. } else if ref, ok := col.Expr.(*parser.ColumnRef); ok {
  6301. columns = append(columns, ref.Column)
  6302. } else {
  6303. columns = append(columns, fmt.Sprintf("column%d", len(columns)+1))
  6304. }
  6305. }
  6306. return columns
  6307. }
  6308. func (e *Executor) hasAggregates(columns []parser.SelectColumn) bool {
  6309. for _, col := range columns {
  6310. if e.isAggregate(col.Expr) {
  6311. return true
  6312. }
  6313. }
  6314. return false
  6315. }
  6316. func (e *Executor) isAggregate(expr parser.Expr) bool {
  6317. if _, ok := expr.(*parser.WindowExpr); ok {
  6318. // Window functions are computed after grouping; they are not aggregates.
  6319. return false
  6320. }
  6321. if fn, ok := expr.(*parser.FunctionCall); ok {
  6322. name := strings.ToUpper(fn.Name)
  6323. if isAggregateCallName(name) {
  6324. return true
  6325. }
  6326. // Non-aggregate function: check if any arg contains an aggregate.
  6327. for _, arg := range fn.Args {
  6328. if e.isAggregate(arg) {
  6329. return true
  6330. }
  6331. }
  6332. return false
  6333. }
  6334. switch ex := expr.(type) {
  6335. case *parser.UnaryExpr:
  6336. return e.isAggregate(ex.Operand)
  6337. case *parser.BinaryExpr:
  6338. return e.isAggregate(ex.Left) || e.isAggregate(ex.Right)
  6339. case *parser.ParenExpr:
  6340. return e.isAggregate(ex.Expr)
  6341. case *parser.CaseExpr:
  6342. if ex.Operand != nil && e.isAggregate(ex.Operand) {
  6343. return true
  6344. }
  6345. for _, w := range ex.Whens {
  6346. if e.isAggregate(w.Condition) || e.isAggregate(w.Result) {
  6347. return true
  6348. }
  6349. }
  6350. if ex.Else != nil {
  6351. return e.isAggregate(ex.Else)
  6352. }
  6353. case *parser.CastExpr:
  6354. return e.isAggregate(ex.Expr)
  6355. case *parser.IsNullExpr:
  6356. return e.isAggregate(ex.Left)
  6357. case *parser.IsDistinctExpr:
  6358. return e.isAggregate(ex.Left) || e.isAggregate(ex.Right)
  6359. case *parser.BetweenExpr:
  6360. return e.isAggregate(ex.Left) || e.isAggregate(ex.Low) || e.isAggregate(ex.High)
  6361. case *parser.InExpr:
  6362. if e.isAggregate(ex.Left) {
  6363. return true
  6364. }
  6365. for _, val := range ex.Values {
  6366. if e.isAggregate(val) {
  6367. return true
  6368. }
  6369. }
  6370. return false
  6371. }
  6372. return false
  6373. }
  6374. // resolveGroupByAliases replaces GROUP BY references that name a SELECT alias
  6375. // with the aliased expression. SQLite allows `GROUP BY alias`, so grouping must
  6376. // use the same expression the projection evaluates.
  6377. func (e *Executor) resolveGroupByAliases(groupBy []parser.Expr, selectCols []parser.SelectColumn) []parser.Expr {
  6378. if len(groupBy) == 0 {
  6379. return groupBy
  6380. }
  6381. aliases := make(map[string]parser.Expr, len(selectCols))
  6382. for _, col := range selectCols {
  6383. if col.Alias != "" && col.Expr != nil {
  6384. aliases[strings.ToUpper(col.Alias)] = col.Expr
  6385. }
  6386. }
  6387. if len(aliases) == 0 {
  6388. return groupBy
  6389. }
  6390. out := make([]parser.Expr, len(groupBy))
  6391. for i, expr := range groupBy {
  6392. if ref, ok := expr.(*parser.ColumnRef); ok {
  6393. if target, ok := aliases[strings.ToUpper(ref.Column)]; ok {
  6394. out[i] = target
  6395. continue
  6396. }
  6397. }
  6398. out[i] = expr
  6399. }
  6400. return out
  6401. }
  6402. func (e *Executor) buildGroupKey(groupBy []parser.Expr, row storage.Row) string {
  6403. var parts []string
  6404. for _, expr := range groupBy {
  6405. val, _ := e.evalExpr(expr, row)
  6406. parts = append(parts, fmt.Sprintf("%v", val))
  6407. }
  6408. return strings.Join(parts, "|")
  6409. }
  6410. // resolveOrderByPositions replaces positional ORDER BY expressions (e.g. ORDER BY 1)
  6411. // with the corresponding SELECT column expressions per SQL-92 semantics.
  6412. func resolveOrderByPositions(orderBy []parser.OrderByItem, selectCols []parser.SelectColumn) []parser.OrderByItem {
  6413. result := make([]parser.OrderByItem, len(orderBy))
  6414. for i, item := range orderBy {
  6415. if lit, ok := item.Expr.(*parser.LiteralExpr); ok {
  6416. if pos, err := strconv.Atoi(lit.Value); err == nil && pos >= 1 && pos <= len(selectCols) {
  6417. col := selectCols[pos-1]
  6418. if col.Expr != nil {
  6419. result[i] = parser.OrderByItem{Expr: col.Expr, Desc: item.Desc, NullsOrder: item.NullsOrder}
  6420. continue
  6421. }
  6422. }
  6423. }
  6424. result[i] = item
  6425. }
  6426. return result
  6427. }
  6428. // orderByLess reports whether key slice a sorts before b under orderBy.
  6429. // Keys are precomputed per-row ORDER BY expression values, one per item.
  6430. func orderByLess(a, b []interface{}, orderBy []parser.OrderByItem) bool {
  6431. for i, item := range orderBy {
  6432. av, bv := a[i], b[i]
  6433. if av == nil || bv == nil {
  6434. if av == nil && bv == nil {
  6435. continue
  6436. }
  6437. // SQLite treats NULL as smaller than any value, so the default puts
  6438. // NULLs first for ASC and last for DESC. NULLS FIRST/LAST overrides it.
  6439. nullsFirst := !item.Desc
  6440. switch item.NullsOrder {
  6441. case parser.NullsFirst:
  6442. nullsFirst = true
  6443. case parser.NullsLast:
  6444. nullsFirst = false
  6445. }
  6446. if av == nil {
  6447. return nullsFirst
  6448. }
  6449. return !nullsFirst
  6450. }
  6451. cmp := compare(av, bv)
  6452. if cmp != 0 {
  6453. if item.Desc {
  6454. return cmp > 0
  6455. }
  6456. return cmp < 0
  6457. }
  6458. }
  6459. return false
  6460. }
  6461. // sortKeyOrder returns a permutation of [0..len(keys)) that sorts the keys
  6462. // ascending per orderBy.
  6463. func sortKeyOrder(keys [][]interface{}, orderBy []parser.OrderByItem) []int {
  6464. order := make([]int, len(keys))
  6465. for i := range order {
  6466. order[i] = i
  6467. }
  6468. sort.Slice(order, func(a, b int) bool {
  6469. return orderByLess(keys[order[a]], keys[order[b]], orderBy)
  6470. })
  6471. return order
  6472. }
  6473. // topNHeap is a bounded max-heap that keeps the k smallest elements (per
  6474. // orderByLess) seen so far.
  6475. type topNHeap struct {
  6476. keys [][]interface{}
  6477. idx []int
  6478. orderBy []parser.OrderByItem
  6479. }
  6480. func (h *topNHeap) Len() int { return len(h.idx) }
  6481. func (h *topNHeap) Less(i, j int) bool {
  6482. return orderByLess(h.keys[h.idx[j]], h.keys[h.idx[i]], h.orderBy)
  6483. }
  6484. func (h *topNHeap) Swap(i, j int) { h.idx[i], h.idx[j] = h.idx[j], h.idx[i] }
  6485. func (h *topNHeap) Push(x interface{}) { h.idx = append(h.idx, x.(int)) }
  6486. func (h *topNHeap) Pop() interface{} {
  6487. n := len(h.idx)
  6488. x := h.idx[n-1]
  6489. h.idx = h.idx[:n-1]
  6490. return x
  6491. }
  6492. // topNKeyOrder returns the indices of the k smallest keys (per orderByLess) in
  6493. // ascending order, without fully sorting all n elements. If k >= n it falls
  6494. // back to a full sort.
  6495. func topNKeyOrder(keys [][]interface{}, orderBy []parser.OrderByItem, k int) []int {
  6496. if k <= 0 {
  6497. return nil
  6498. }
  6499. if k >= len(keys) {
  6500. return sortKeyOrder(keys, orderBy)
  6501. }
  6502. h := &topNHeap{keys: keys, orderBy: orderBy, idx: make([]int, 0, k)}
  6503. for i := range keys {
  6504. if h.Len() < k {
  6505. heap.Push(h, i)
  6506. } else if orderByLess(keys[i], keys[h.idx[0]], orderBy) {
  6507. h.idx[0] = i
  6508. heap.Fix(h, 0)
  6509. }
  6510. }
  6511. selected := append([]int(nil), h.idx...)
  6512. sort.Slice(selected, func(a, b int) bool {
  6513. return orderByLess(keys[selected[a]], keys[selected[b]], orderBy)
  6514. })
  6515. return selected
  6516. }
  6517. func reorderRows(rows []storage.Row, order []int) {
  6518. tmp := make([]storage.Row, len(rows))
  6519. for i, idx := range order {
  6520. tmp[i] = rows[idx]
  6521. }
  6522. copy(rows, tmp)
  6523. }
  6524. // sortRowKeys precomputes the ORDER BY expression value for each row so each
  6525. // expression is evaluated once per row instead of O(n log n) times.
  6526. func (e *Executor) sortRowKeys(rows []storage.Row, orderBy []parser.OrderByItem) [][]interface{} {
  6527. keys := make([][]interface{}, len(rows))
  6528. for i, row := range rows {
  6529. ks := make([]interface{}, len(orderBy))
  6530. for j, item := range orderBy {
  6531. ks[j], _ = e.evalExpr(item.Expr, row)
  6532. }
  6533. keys[i] = ks
  6534. }
  6535. return keys
  6536. }
  6537. func (e *Executor) sortRows(rows []storage.Row, orderBy []parser.OrderByItem) {
  6538. order := sortKeyOrder(e.sortRowKeys(rows, orderBy), orderBy)
  6539. reorderRows(rows, order)
  6540. }
  6541. // topNRows sorts only enough to keep the k smallest rows (per orderBy).
  6542. func (e *Executor) topNRows(rows []storage.Row, orderBy []parser.OrderByItem, k int) []storage.Row {
  6543. order := topNKeyOrder(e.sortRowKeys(rows, orderBy), orderBy, k)
  6544. out := make([]storage.Row, len(order))
  6545. for i, idx := range order {
  6546. out[i] = rows[idx]
  6547. }
  6548. return out
  6549. }
  6550. // orderAndLimitRows applies ORDER BY (with a bounded top-N selection when a
  6551. // LIMIT is present), then OFFSET and LIMIT, preserving SQL semantics.
  6552. func (e *Executor) orderAndLimitRows(rows []storage.Row, orderBy []parser.OrderByItem, limitExpr, offsetExpr parser.Expr, selectCols []parser.SelectColumn) []storage.Row {
  6553. orderBy = resolveOrderByPositions(orderBy, selectCols)
  6554. var offset, limit int
  6555. hasOffset := offsetExpr != nil
  6556. hasLimit := limitExpr != nil
  6557. if hasOffset {
  6558. offset = e.evalIntExpr(offsetExpr)
  6559. }
  6560. if hasLimit {
  6561. limit = e.evalIntExpr(limitExpr)
  6562. }
  6563. if len(orderBy) > 0 {
  6564. if hasLimit && limit >= 0 {
  6565. k := offset + limit
  6566. if k >= 0 && k < len(rows) {
  6567. rows = e.topNRows(rows, orderBy, k)
  6568. } else {
  6569. e.sortRows(rows, orderBy)
  6570. }
  6571. } else {
  6572. e.sortRows(rows, orderBy)
  6573. }
  6574. }
  6575. if hasOffset {
  6576. if offset < len(rows) {
  6577. rows = rows[offset:]
  6578. } else {
  6579. rows = nil
  6580. }
  6581. }
  6582. if hasLimit {
  6583. if limit < len(rows) {
  6584. rows = rows[:limit]
  6585. }
  6586. }
  6587. return rows
  6588. }
  6589. // resultRowKey evaluates a single ORDER BY item against a result row, honoring
  6590. // select-column aliases exactly like the previous sortResultRows implementation.
  6591. func (e *Executor) resultRowKey(result *Result, rowIdx int, item parser.OrderByItem, columnNames []string) interface{} {
  6592. if ref, ok := item.Expr.(*parser.ColumnRef); ok && ref.Table == "" {
  6593. for idx, name := range columnNames {
  6594. if strings.EqualFold(name, ref.Column) {
  6595. if idx < len(result.Rows[rowIdx]) {
  6596. return result.Rows[rowIdx][idx]
  6597. }
  6598. }
  6599. }
  6600. }
  6601. row := e.resultRowToStorageRow(result, rowIdx)
  6602. v, _ := e.evalExpr(item.Expr, row)
  6603. return v
  6604. }
  6605. // resultRowKeys precomputes the ORDER BY expression value for each result row.
  6606. func (e *Executor) resultRowKeys(result *Result, orderBy []parser.OrderByItem, columnNames []string) [][]interface{} {
  6607. keys := make([][]interface{}, len(result.Rows))
  6608. for i := range result.Rows {
  6609. ks := make([]interface{}, len(orderBy))
  6610. for j, item := range orderBy {
  6611. ks[j] = e.resultRowKey(result, i, item, columnNames)
  6612. }
  6613. keys[i] = ks
  6614. }
  6615. return keys
  6616. }
  6617. // sortResultRows sorts Result.Rows based on ORDER BY clauses.
  6618. // It handles column aliases by matching them against the select columns.
  6619. func (e *Executor) sortResultRows(result *Result, orderBy []parser.OrderByItem, selectColumns []parser.SelectColumn, columnNames []string) {
  6620. orderBy = resolveOrderByPositions(orderBy, selectColumns)
  6621. order := sortKeyOrder(e.resultRowKeys(result, orderBy, columnNames), orderBy)
  6622. rows := make([][]interface{}, len(order))
  6623. for i, idx := range order {
  6624. rows[i] = result.Rows[idx]
  6625. }
  6626. result.Rows = rows
  6627. }
  6628. // orderAndLimitResultRows applies ORDER BY (with bounded top-N selection when a
  6629. // LIMIT is present), then OFFSET and LIMIT, to a Result's rows.
  6630. func (e *Executor) orderAndLimitResultRows(result *Result, orderBy []parser.OrderByItem, limitExpr, offsetExpr parser.Expr, selectCols []parser.SelectColumn, columnNames []string) {
  6631. orderBy = resolveOrderByPositions(orderBy, selectCols)
  6632. var offset, limit int
  6633. hasOffset := offsetExpr != nil
  6634. hasLimit := limitExpr != nil
  6635. if hasOffset {
  6636. offset = e.evalIntExpr(offsetExpr)
  6637. }
  6638. if hasLimit {
  6639. limit = e.evalIntExpr(limitExpr)
  6640. }
  6641. if len(orderBy) > 0 {
  6642. if hasLimit && limit >= 0 {
  6643. k := offset + limit
  6644. if k >= 0 && k < len(result.Rows) {
  6645. order := topNKeyOrder(e.resultRowKeys(result, orderBy, columnNames), orderBy, k)
  6646. rows := make([][]interface{}, len(order))
  6647. for i, idx := range order {
  6648. rows[i] = result.Rows[idx]
  6649. }
  6650. result.Rows = rows
  6651. } else {
  6652. e.sortResultRows(result, orderBy, nil, columnNames)
  6653. }
  6654. } else {
  6655. e.sortResultRows(result, orderBy, nil, columnNames)
  6656. }
  6657. }
  6658. if hasOffset {
  6659. if offset < len(result.Rows) {
  6660. result.Rows = result.Rows[offset:]
  6661. } else {
  6662. result.Rows = nil
  6663. }
  6664. result.RowCount = len(result.Rows)
  6665. }
  6666. if hasLimit {
  6667. if limit < len(result.Rows) {
  6668. result.Rows = result.Rows[:limit]
  6669. }
  6670. result.RowCount = len(result.Rows)
  6671. }
  6672. }
  6673. // resultRowToStorageRow converts a Result row back to storage.Row for expression evaluation.
  6674. func (e *Executor) resultRowToStorageRow(result *Result, rowIdx int) storage.Row {
  6675. row := make(storage.Row)
  6676. for colIdx, colName := range result.Columns {
  6677. if colIdx < len(result.Rows[rowIdx]) {
  6678. row[colName] = result.Rows[rowIdx][colIdx]
  6679. }
  6680. }
  6681. return row
  6682. }
  6683. func (e *Executor) evalIntExpr(expr parser.Expr) int {
  6684. val, _ := e.evalExpr(expr, nil)
  6685. return int(toFloat(val))
  6686. }
  6687. // Type conversion helpers
  6688. func isIntVal(v interface{}) bool {
  6689. switch v.(type) {
  6690. case int64, int, bool:
  6691. return true
  6692. default:
  6693. return false
  6694. }
  6695. }
  6696. func toInt64(v interface{}) int64 {
  6697. switch val := v.(type) {
  6698. case int64:
  6699. return val
  6700. case int:
  6701. return int64(val)
  6702. case float64:
  6703. return int64(val)
  6704. case bool:
  6705. if val {
  6706. return 1
  6707. }
  6708. return 0
  6709. case jsonText:
  6710. // -> returns JSON text, so integer conversion parses its text form.
  6711. // Keep exact integers exact before falling back to float truncation.
  6712. if i, err := strconv.ParseInt(string(val), 10, 64); err == nil {
  6713. return i
  6714. }
  6715. f, _ := strconv.ParseFloat(string(val), 64)
  6716. return int64(f)
  6717. default:
  6718. return 0
  6719. }
  6720. }
  6721. func toFloat(v interface{}) float64 {
  6722. switch val := v.(type) {
  6723. case nil:
  6724. return 0
  6725. case int64:
  6726. return float64(val)
  6727. case int:
  6728. return float64(val)
  6729. case float64:
  6730. return val
  6731. case bool:
  6732. if val {
  6733. return 1
  6734. }
  6735. return 0
  6736. case string:
  6737. f, _ := strconv.ParseFloat(val, 64)
  6738. return f
  6739. case jsonText:
  6740. f, _ := strconv.ParseFloat(string(val), 64)
  6741. return f
  6742. default:
  6743. return 0
  6744. }
  6745. }
  6746. func toBool(v interface{}) bool {
  6747. switch val := v.(type) {
  6748. case nil:
  6749. return false
  6750. case bool:
  6751. return val
  6752. case int64:
  6753. return val != 0
  6754. case int:
  6755. return val != 0
  6756. case float64:
  6757. return val != 0
  6758. case string:
  6759. return val != "" && val != "0" && strings.ToLower(val) != "false"
  6760. case jsonText:
  6761. s := string(val)
  6762. return s != "" && s != "0" && strings.ToLower(s) != "false"
  6763. default:
  6764. return false
  6765. }
  6766. }
  6767. func toString(v interface{}) string {
  6768. if v == nil {
  6769. return ""
  6770. }
  6771. switch t := v.(type) {
  6772. case string:
  6773. return t
  6774. case []byte:
  6775. return string(t)
  6776. case jsonText:
  6777. return string(t)
  6778. case bool:
  6779. if t {
  6780. return "1"
  6781. }
  6782. return "0"
  6783. case int:
  6784. return strconv.FormatInt(int64(t), 10)
  6785. case int64:
  6786. return strconv.FormatInt(t, 10)
  6787. case uint:
  6788. return strconv.FormatUint(uint64(t), 10)
  6789. case uint64:
  6790. return strconv.FormatUint(t, 10)
  6791. case float32:
  6792. return formatSQLiteReal(float64(t))
  6793. case float64:
  6794. return formatSQLiteReal(t)
  6795. default:
  6796. return fmt.Sprintf("%v", v)
  6797. }
  6798. }
  6799. func compare(a, b interface{}) int {
  6800. if a == nil && b == nil {
  6801. return 0
  6802. }
  6803. if a == nil {
  6804. return -1
  6805. }
  6806. if b == nil {
  6807. return 1
  6808. }
  6809. // Try numeric comparison
  6810. fa, oka := toNumeric(a)
  6811. fb, okb := toNumeric(b)
  6812. if oka && okb {
  6813. if fa < fb {
  6814. return -1
  6815. }
  6816. if fa > fb {
  6817. return 1
  6818. }
  6819. return 0
  6820. }
  6821. // String comparison
  6822. sa := toString(a)
  6823. sb := toString(b)
  6824. return strings.Compare(sa, sb)
  6825. }
  6826. func toNumeric(v interface{}) (float64, bool) {
  6827. switch val := v.(type) {
  6828. case int64:
  6829. return float64(val), true
  6830. case int:
  6831. return float64(val), true
  6832. case float64:
  6833. return val, true
  6834. case string:
  6835. f, err := strconv.ParseFloat(val, 64)
  6836. return f, err == nil
  6837. case jsonText:
  6838. f, err := strconv.ParseFloat(string(val), 64)
  6839. return f, err == nil
  6840. default:
  6841. return 0, false
  6842. }
  6843. }
  6844. // splitANDClauses flattens a tree of AND binary expressions into a slice of leaf conditions.
  6845. func splitANDClauses(expr parser.Expr) []parser.Expr {
  6846. if bin, ok := expr.(*parser.BinaryExpr); ok && bin.Op == lexer.TokenAND {
  6847. left := splitANDClauses(bin.Left)
  6848. right := splitANDClauses(bin.Right)
  6849. return append(left, right...)
  6850. }
  6851. return []parser.Expr{expr}
  6852. }
  6853. // collectColumnRefs returns all unqualified column names referenced in an expression.
  6854. func collectColumnRefs(expr parser.Expr) []string {
  6855. var refs []string
  6856. var hasSubquery bool
  6857. var walk func(parser.Expr)
  6858. walk = func(e parser.Expr) {
  6859. if e == nil {
  6860. return
  6861. }
  6862. switch n := e.(type) {
  6863. case *parser.ColumnRef:
  6864. refs = append(refs, n.Column)
  6865. case *parser.BinaryExpr:
  6866. walk(n.Left)
  6867. walk(n.Right)
  6868. case *parser.UnaryExpr:
  6869. walk(n.Operand)
  6870. case *parser.InExpr:
  6871. walk(n.Left)
  6872. // Check for subquery
  6873. if n.Subquery != nil {
  6874. hasSubquery = true
  6875. }
  6876. for _, v := range n.Values {
  6877. walk(v)
  6878. }
  6879. case *parser.BetweenExpr:
  6880. walk(n.Left)
  6881. walk(n.Low)
  6882. walk(n.High)
  6883. case *parser.LikeExpr:
  6884. walk(n.Left)
  6885. walk(n.Pattern)
  6886. case *parser.IsNullExpr:
  6887. walk(n.Left)
  6888. case *parser.IsDistinctExpr:
  6889. walk(n.Left)
  6890. walk(n.Right)
  6891. case *parser.CaseExpr:
  6892. walk(n.Operand)
  6893. for _, w := range n.Whens {
  6894. walk(w.Condition)
  6895. walk(w.Result)
  6896. }
  6897. walk(n.Else)
  6898. case *parser.FunctionCall:
  6899. for _, a := range n.Args {
  6900. walk(a)
  6901. }
  6902. case *parser.ParenExpr:
  6903. walk(n.Expr)
  6904. case *parser.CastExpr:
  6905. walk(n.Expr)
  6906. case *parser.SubqueryExpr:
  6907. // Subqueries may reference outer columns
  6908. hasSubquery = true
  6909. case *parser.ExistsExpr:
  6910. // EXISTS subqueries may reference outer columns
  6911. hasSubquery = true
  6912. case *parser.LiteralExpr:
  6913. // Literals have no column refs
  6914. }
  6915. }
  6916. walk(expr)
  6917. // If we have subqueries, add a sentinel value to indicate non-constant
  6918. if hasSubquery {
  6919. refs = append(refs, "__subquery__")
  6920. }
  6921. return refs
  6922. }
  6923. type tableColRef struct{ tbl, col string }
  6924. // collectTableColumnRefs returns all column references with their table qualifier (may be "").
  6925. func collectTableColumnRefs(expr parser.Expr) []tableColRef {
  6926. var refs []tableColRef
  6927. var walk func(parser.Expr)
  6928. walk = func(e parser.Expr) {
  6929. if e == nil {
  6930. return
  6931. }
  6932. switch n := e.(type) {
  6933. case *parser.ColumnRef:
  6934. refs = append(refs, tableColRef{tbl: n.Table, col: n.Column})
  6935. case *parser.BinaryExpr:
  6936. walk(n.Left)
  6937. walk(n.Right)
  6938. case *parser.UnaryExpr:
  6939. walk(n.Operand)
  6940. case *parser.InExpr:
  6941. walk(n.Left)
  6942. for _, v := range n.Values {
  6943. walk(v)
  6944. }
  6945. case *parser.BetweenExpr:
  6946. walk(n.Left)
  6947. walk(n.Low)
  6948. walk(n.High)
  6949. case *parser.LikeExpr:
  6950. walk(n.Left)
  6951. walk(n.Pattern)
  6952. case *parser.IsNullExpr:
  6953. walk(n.Left)
  6954. case *parser.IsDistinctExpr:
  6955. walk(n.Left)
  6956. walk(n.Right)
  6957. case *parser.CaseExpr:
  6958. walk(n.Operand)
  6959. for _, w := range n.Whens {
  6960. walk(w.Condition)
  6961. walk(w.Result)
  6962. }
  6963. walk(n.Else)
  6964. case *parser.FunctionCall:
  6965. for _, a := range n.Args {
  6966. walk(a)
  6967. }
  6968. }
  6969. }
  6970. walk(expr)
  6971. return refs
  6972. }
  6973. // combineAND combines a list of expressions with AND.
  6974. func combineAND(clauses []parser.Expr) parser.Expr {
  6975. if len(clauses) == 0 {
  6976. return nil
  6977. }
  6978. result := clauses[0]
  6979. for _, c := range clauses[1:] {
  6980. result = &parser.BinaryExpr{Left: result, Op: lexer.TokenAND, Right: c}
  6981. }
  6982. return result
  6983. }
  6984. // matchLike matches a string against a SQL LIKE pattern.
  6985. func matchLike(s, pattern string) bool {
  6986. // Simple implementation - convert to lowercase for case-insensitive matching
  6987. s = strings.ToLower(s)
  6988. pattern = strings.ToLower(pattern)
  6989. return matchLikeHelper(s, pattern)
  6990. }
  6991. func matchLikeHelper(s, p string) bool {
  6992. if p == "" {
  6993. return s == ""
  6994. }
  6995. if p[0] == '%' {
  6996. // % matches any sequence
  6997. for i := 0; i <= len(s); i++ {
  6998. if matchLikeHelper(s[i:], p[1:]) {
  6999. return true
  7000. }
  7001. }
  7002. return false
  7003. }
  7004. if s == "" {
  7005. return false
  7006. }
  7007. if p[0] == '_' || p[0] == s[0] {
  7008. return matchLikeHelper(s[1:], p[1:])
  7009. }
  7010. return false
  7011. }
  7012. // matchGlob matches a string against a GLOB pattern.
  7013. // GLOB uses * for any sequence and ? for single character (case-sensitive).
  7014. func matchGlob(pattern, s string) bool {
  7015. return matchGlobHelper(pattern, s)
  7016. }
  7017. func matchGlobHelper(p, s string) bool {
  7018. if p == "" {
  7019. return s == ""
  7020. }
  7021. if p[0] == '*' {
  7022. // * matches any sequence
  7023. for i := 0; i <= len(s); i++ {
  7024. if matchGlobHelper(p[1:], s[i:]) {
  7025. return true
  7026. }
  7027. }
  7028. return false
  7029. }
  7030. if s == "" {
  7031. return false
  7032. }
  7033. if p[0] == '?' || p[0] == s[0] {
  7034. return matchGlobHelper(p[1:], s[1:])
  7035. }
  7036. // Handle character classes [...]
  7037. if p[0] == '[' {
  7038. end := strings.Index(p, "]")
  7039. if end > 0 {
  7040. class := p[1:end]
  7041. match := false
  7042. negate := false
  7043. if len(class) > 0 && class[0] == '^' {
  7044. negate = true
  7045. class = class[1:]
  7046. }
  7047. for _, c := range class {
  7048. if byte(c) == s[0] {
  7049. match = true
  7050. break
  7051. }
  7052. }
  7053. if negate {
  7054. match = !match
  7055. }
  7056. if match {
  7057. return matchGlobHelper(p[end+1:], s[1:])
  7058. }
  7059. }
  7060. }
  7061. return false
  7062. }
  7063. // applyDistinct removes duplicate rows from the result
  7064. func (e *Executor) applyDistinct(rows [][]interface{}) [][]interface{} {
  7065. if len(rows) == 0 {
  7066. return rows
  7067. }
  7068. seen := make(map[string]bool)
  7069. uniqueRows := make([][]interface{}, 0)
  7070. for _, row := range rows {
  7071. // Create a key from all column values
  7072. key := ""
  7073. for i, val := range row {
  7074. if i > 0 {
  7075. key += "\x00" // Use null byte as separator
  7076. }
  7077. key += fmt.Sprintf("%v", val)
  7078. }
  7079. if !seen[key] {
  7080. seen[key] = true
  7081. uniqueRows = append(uniqueRows, row)
  7082. }
  7083. }
  7084. return uniqueRows
  7085. }