2
0

executor.go 198 KB

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