executor.go 237 KB

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