executor.go 198 KB

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