executor.go 210 KB

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