2
0

executor.go 187 KB

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