executor.go 205 KB

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