2
0

executor.go 200 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576
  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. A constant DEFAULT is
  3790. // written into every existing row (see SchemaManager.AddColumn), so the column
  3791. // reads the default on rows that predate the statement as well as on later
  3792. // INSERTs that omit it.
  3793. func (e *Executor) executeAlterTableAddColumn(table string, action *parser.AddColumnAction) (*Result, error) {
  3794. schema, err := e.schema.GetSchema(table)
  3795. if err != nil {
  3796. return nil, err
  3797. }
  3798. if _, exists := schema.GetColumn(action.Column.Name); exists {
  3799. if action.IfNotExists {
  3800. return NewResult("ALTER TABLE"), nil
  3801. }
  3802. return nil, fmt.Errorf("column already exists: %s", action.Column.Name)
  3803. }
  3804. col := storage.Column{
  3805. Name: action.Column.Name,
  3806. Type: action.Column.Type.Name,
  3807. Nullable: true,
  3808. }
  3809. var uniqueConstraint *parser.ColumnConstraint
  3810. // Process column constraints
  3811. for _, constraint := range action.Column.Constraints {
  3812. switch constraint.Type {
  3813. case parser.ConstraintPrimaryKey:
  3814. col.PrimaryKey = true
  3815. col.Nullable = false
  3816. case parser.ConstraintNotNull:
  3817. col.Nullable = false
  3818. case parser.ConstraintUnique:
  3819. unique := constraint
  3820. uniqueConstraint = &unique
  3821. case parser.ConstraintDefault:
  3822. if constraint.Default != nil {
  3823. val, err := constantDefaultValue(e, col.Name, constraint.Default)
  3824. if err != nil {
  3825. return nil, err
  3826. }
  3827. col.Default = val
  3828. }
  3829. case parser.ConstraintCheck:
  3830. return nil, pgerror.Unsupported(
  3831. "CHECK constraints are not supported: column %q declares CHECK; enforce the rule in the application instead",
  3832. col.Name,
  3833. )
  3834. case parser.ConstraintForeignKey:
  3835. return nil, pgerror.Unsupported(
  3836. "FOREIGN KEY constraints are not supported: column %q declares REFERENCES %s; enforce referential integrity in the application instead",
  3837. col.Name, constraint.RefTable,
  3838. )
  3839. }
  3840. }
  3841. var uniqueIndex *storage.Index
  3842. if uniqueConstraint != nil {
  3843. uniqueIndex = e.addColumnUniqueIndex(table, col.Name, uniqueConstraint)
  3844. }
  3845. // The schema manager validates the new column against durable rows, rewrites
  3846. // them, and publishes the column together with its UNIQUE index while holding
  3847. // the table's exclusive gate, so a writer cannot slip a row in between the
  3848. // validation and the publication. Rows this session staged in an open
  3849. // transaction are invisible to that scan, so reject them here as well; the
  3850. // commit re-validates them against the schema that is current by then.
  3851. if !col.Nullable && col.Default == nil {
  3852. stagedRows, err := e.session.CountFast(table)
  3853. if err != nil {
  3854. return nil, err
  3855. }
  3856. if stagedRows > 0 {
  3857. return nil, &storage.NotNullViolationError{Table: table, Column: col.Name}
  3858. }
  3859. }
  3860. if err := e.schema.AddColumn(table, col, uniqueIndex); err != nil {
  3861. if action.IfNotExists && strings.Contains(err.Error(), "column already exists") {
  3862. return NewResult("ALTER TABLE"), nil
  3863. }
  3864. return nil, err
  3865. }
  3866. // Update catalog
  3867. e.SyncCatalog()
  3868. result := NewResult("ALTER TABLE")
  3869. return result, nil
  3870. }
  3871. // addColumnUniqueIndex names the index an ADD COLUMN ... UNIQUE constraint
  3872. // materializes, using the declared constraint name when there is one and the
  3873. // same deterministic internal name CREATE TABLE gives an unnamed column-level
  3874. // UNIQUE constraint otherwise, suffixing collisions.
  3875. func (e *Executor) addColumnUniqueIndex(table, column string, constraint *parser.ColumnConstraint) *storage.Index {
  3876. base := "uniq_" + strings.ToLower(table) + "_" + strings.ToLower(column)
  3877. if constraint.Name != "" {
  3878. base = constraint.Name
  3879. }
  3880. name := base
  3881. for n := 2; e.schema.IndexExists(name); n++ {
  3882. name = fmt.Sprintf("%s_%d", base, n)
  3883. }
  3884. index := &storage.Index{
  3885. Name: name,
  3886. Table: table,
  3887. Unique: true,
  3888. Columns: []storage.IndexColumn{{Name: column}},
  3889. }
  3890. if constraint.HasOnConflict {
  3891. index.OnConflict = conflictActionName(constraint.OnConflict)
  3892. }
  3893. return index
  3894. }
  3895. // executeAlterTableDropColumn drops a column from a table.
  3896. func (e *Executor) executeAlterTableDropColumn(table string, action *parser.DropColumnAction) (*Result, error) {
  3897. if err := e.schema.DropColumn(table, action.Column); err != nil {
  3898. return nil, err
  3899. }
  3900. // Update catalog
  3901. e.SyncCatalog()
  3902. result := NewResult("ALTER TABLE")
  3903. return result, nil
  3904. }
  3905. // executeAlterTableRename renames a table.
  3906. func (e *Executor) executeAlterTableRename(table string, action *parser.RenameTableAction) (*Result, error) {
  3907. if err := e.schema.RenameTable(table, action.NewName); err != nil {
  3908. return nil, err
  3909. }
  3910. e.session.InvalidateCache(table)
  3911. e.session.InvalidateCache(action.NewName)
  3912. // Update catalog
  3913. e.SyncCatalog()
  3914. result := NewResult("ALTER TABLE")
  3915. return result, nil
  3916. }
  3917. // executeAlterTableRenameColumn renames a column.
  3918. func (e *Executor) executeAlterTableRenameColumn(table string, action *parser.RenameColumnAction) (*Result, error) {
  3919. if err := e.schema.RenameColumn(table, action.OldName, action.NewName); err != nil {
  3920. return nil, err
  3921. }
  3922. // Update catalog
  3923. e.SyncCatalog()
  3924. result := NewResult("ALTER TABLE")
  3925. return result, nil
  3926. }
  3927. // Transaction execution methods
  3928. // executeBegin starts a new transaction.
  3929. func (e *Executor) executeBegin(stmt *parser.BeginStmt) (*Result, error) {
  3930. if e.inTransaction {
  3931. return nil, fmt.Errorf("cannot start a transaction within a transaction")
  3932. }
  3933. if err := e.session.Begin(); err != nil {
  3934. return nil, err
  3935. }
  3936. e.inTransaction = true
  3937. e.savepoints = nil
  3938. e.savepointPositions = nil
  3939. e.clearNotificationState()
  3940. result := NewResult("BEGIN")
  3941. return result, nil
  3942. }
  3943. // executeCommit commits the current transaction.
  3944. func (e *Executor) executeCommit(stmt *parser.CommitStmt) (*Result, error) {
  3945. if !e.inTransaction {
  3946. return nil, fmt.Errorf("cannot commit: no transaction in progress")
  3947. }
  3948. lsn, err := e.session.CommitWithLSN()
  3949. if err != nil {
  3950. e.inTransaction = false
  3951. e.savepoints = nil
  3952. e.savepointPositions = nil
  3953. e.finishRollback()
  3954. return nil, err
  3955. }
  3956. e.inTransaction = false
  3957. e.savepoints = nil
  3958. e.savepointPositions = nil
  3959. e.finishCommit(lsn)
  3960. result := NewResult("COMMIT")
  3961. result.LSN = lsn
  3962. return result, nil
  3963. }
  3964. // executeRollback rolls back the current transaction or to a savepoint.
  3965. func (e *Executor) executeRollback(stmt *parser.RollbackStmt) (*Result, error) {
  3966. if !e.inTransaction {
  3967. return nil, fmt.Errorf("cannot rollback: no transaction in progress")
  3968. }
  3969. if stmt.Savepoint != "" {
  3970. // Rollback to savepoint
  3971. return e.rollbackToSavepoint(stmt.Savepoint)
  3972. }
  3973. if err := e.session.Rollback(); err != nil {
  3974. return nil, err
  3975. }
  3976. e.inTransaction = false
  3977. e.savepoints = nil
  3978. e.savepointPositions = nil
  3979. e.finishRollback()
  3980. // total_changes() is monotonic (SQLite semantics): it is NOT decremented on
  3981. // rollback. last_insert_rowid() and changes() also intentionally hold.
  3982. result := NewResult("ROLLBACK")
  3983. return result, nil
  3984. }
  3985. // executeSavepoint creates a savepoint.
  3986. func (e *Executor) executeSavepoint(stmt *parser.SavepointStmt) (*Result, error) {
  3987. if !e.inTransaction {
  3988. // SQLite allows SAVEPOINT outside transaction (starts implicit transaction)
  3989. if err := e.session.Begin(); err != nil {
  3990. return nil, err
  3991. }
  3992. e.inTransaction = true
  3993. e.savepoints = nil
  3994. e.savepointPositions = nil
  3995. e.clearNotificationState()
  3996. }
  3997. // Add savepoint marker
  3998. e.savepoints = append(e.savepoints, stmt.Name)
  3999. e.savepointPositions = append(e.savepointPositions, e.session.Snapshot())
  4000. e.notificationSaves = append(e.notificationSaves, e.notificationSnapshot())
  4001. result := NewResult("SAVEPOINT")
  4002. return result, nil
  4003. }
  4004. // executeRelease releases a savepoint.
  4005. func (e *Executor) executeRelease(stmt *parser.ReleaseStmt) (*Result, error) {
  4006. if !e.inTransaction {
  4007. return nil, fmt.Errorf("cannot release savepoint: no transaction in progress")
  4008. }
  4009. // Find and remove the savepoint
  4010. found := false
  4011. for i := len(e.savepoints) - 1; i >= 0; i-- {
  4012. if e.savepoints[i] == stmt.Name {
  4013. e.savepoints = e.savepoints[:i]
  4014. e.savepointPositions = e.savepointPositions[:i]
  4015. if i <= len(e.notificationSaves) {
  4016. e.notificationSaves = e.notificationSaves[:i]
  4017. }
  4018. found = true
  4019. break
  4020. }
  4021. }
  4022. if !found {
  4023. return nil, fmt.Errorf("no such savepoint: %s", stmt.Name)
  4024. }
  4025. result := NewResult("RELEASE")
  4026. return result, nil
  4027. }
  4028. // executeAttach attaches a database.
  4029. func (e *Executor) executeAttach(stmt *parser.AttachStmt) (*Result, error) {
  4030. // Check if alias already exists
  4031. if _, exists := e.attachedDatabases[stmt.Alias]; exists {
  4032. return nil, fmt.Errorf("database alias already exists: %s", stmt.Alias)
  4033. }
  4034. // Reserved alias check
  4035. if strings.EqualFold(stmt.Alias, "temp") || strings.EqualFold(stmt.Alias, "temporary") {
  4036. return nil, fmt.Errorf("reserved database alias: %s", stmt.Alias)
  4037. }
  4038. // Get the pool from the main schema manager
  4039. pool := e.schema.GetPool()
  4040. // Create new schema and table managers for the attached database
  4041. // In PizzaKV, each database is just a different namespace/prefix
  4042. schema := storage.NewSchemaManager(pool, stmt.FilePath)
  4043. table := storage.NewTableManager(pool, schema, stmt.FilePath)
  4044. // Register the database connection
  4045. e.attachedDatabases[stmt.Alias] = &DatabaseConnection{
  4046. Alias: stmt.Alias,
  4047. Path: stmt.FilePath,
  4048. Schema: schema,
  4049. Table: table,
  4050. }
  4051. // Sync the catalog with the attached database's tables
  4052. tables, _ := schema.ListTables()
  4053. for _, tableName := range tables {
  4054. tSchema, err := schema.GetSchema(tableName)
  4055. if err != nil {
  4056. continue
  4057. }
  4058. // Add with database prefix
  4059. tableInfo := tSchema.ToAnalyzerTableInfo()
  4060. tableInfo.Name = stmt.Alias + "." + tableInfo.Name
  4061. e.catalog.CreateTable(tableInfo)
  4062. }
  4063. result := NewResult("ATTACH")
  4064. return result, nil
  4065. }
  4066. // executeDetach detaches a database.
  4067. func (e *Executor) executeDetach(stmt *parser.DetachStmt) (*Result, error) {
  4068. // Cannot detach main database
  4069. if strings.EqualFold(stmt.Alias, "main") {
  4070. return nil, fmt.Errorf("cannot detach main database")
  4071. }
  4072. // Check if database exists
  4073. if _, exists := e.attachedDatabases[stmt.Alias]; !exists {
  4074. return nil, fmt.Errorf("no such database: %s", stmt.Alias)
  4075. }
  4076. // Remove from attached databases
  4077. delete(e.attachedDatabases, stmt.Alias)
  4078. // Note: We don't remove from catalog as that would be more complex
  4079. // In a production system, we'd need to track which tables belong to which database
  4080. result := NewResult("DETACH")
  4081. return result, nil
  4082. }
  4083. // rollbackToSavepoint rolls back to a specific savepoint.
  4084. func (e *Executor) rollbackToSavepoint(name string) (*Result, error) {
  4085. // Find savepoint index
  4086. savepointIdx := -1
  4087. for i := len(e.savepoints) - 1; i >= 0; i-- {
  4088. if e.savepoints[i] == name {
  4089. savepointIdx = i
  4090. break
  4091. }
  4092. }
  4093. if savepointIdx == -1 {
  4094. return nil, fmt.Errorf("no such savepoint: %s", name)
  4095. }
  4096. logPosition := e.savepointPositions[savepointIdx]
  4097. e.session.RollbackTo(logPosition)
  4098. if savepointIdx < len(e.notificationSaves) {
  4099. e.rollbackNotificationsTo(e.notificationSaves[savepointIdx])
  4100. e.notificationSaves = e.notificationSaves[:savepointIdx+1]
  4101. }
  4102. // Remove savepoints after the target
  4103. e.savepoints = e.savepoints[:savepointIdx+1]
  4104. e.savepointPositions = e.savepointPositions[:savepointIdx+1]
  4105. result := NewResult("ROLLBACK")
  4106. return result, nil
  4107. }
  4108. // RollbackActive rolls back an open transaction, such as when its client
  4109. // disconnects before sending COMMIT or ROLLBACK.
  4110. func (e *Executor) RollbackActive() error {
  4111. if !e.inTransaction {
  4112. return nil
  4113. }
  4114. _, err := e.executeRollback(&parser.RollbackStmt{})
  4115. return err
  4116. }
  4117. // extractIndexableCondition extracts column name and value from a simple equality condition.
  4118. // Returns (column, value, true) if the expression is column = literal.
  4119. func (e *Executor) extractIndexableCondition(expr parser.Expr) (string, interface{}, bool) {
  4120. binExpr, ok := expr.(*parser.BinaryExpr)
  4121. if !ok {
  4122. return "", nil, false
  4123. }
  4124. // Only handle equality for now
  4125. if binExpr.Op != lexer.TokenEq {
  4126. return "", nil, false
  4127. }
  4128. // Check for column = literal pattern
  4129. colRef, leftIsCol := binExpr.Left.(*parser.ColumnRef)
  4130. litExpr, rightIsLit := binExpr.Right.(*parser.LiteralExpr)
  4131. if leftIsCol && rightIsLit && colRef.Table == "" {
  4132. val, _ := e.evalLiteral(litExpr)
  4133. return colRef.Column, val, true
  4134. }
  4135. // Check for literal = column pattern
  4136. litExpr, leftIsLit := binExpr.Left.(*parser.LiteralExpr)
  4137. colRef, rightIsCol := binExpr.Right.(*parser.ColumnRef)
  4138. if leftIsLit && rightIsCol && colRef.Table == "" {
  4139. val, _ := e.evalLiteral(litExpr)
  4140. return colRef.Column, val, true
  4141. }
  4142. return "", nil, false
  4143. }
  4144. // Bound only simple scans. Final OFFSET/LIMIT is still applied once by the
  4145. // normal result path; transactions conservatively retain their full read set.
  4146. func scanLimit(stmt *parser.SelectStmt) (int, bool) {
  4147. if stmt.Limit == nil || len(stmt.From) != 1 || stmt.From[0].Join != nil ||
  4148. stmt.From[0].Alias != "" || stmt.Distinct || len(stmt.GroupBy) != 0 ||
  4149. stmt.Having != nil || len(stmt.OrderBy) != 0 || stmt.Compound != nil || len(stmt.With) != 0 {
  4150. return 0, false
  4151. }
  4152. for _, column := range stmt.Columns {
  4153. switch column.Expr.(type) {
  4154. case *parser.ColumnRef, *parser.LiteralExpr:
  4155. default:
  4156. if !column.Star {
  4157. return 0, false
  4158. }
  4159. }
  4160. }
  4161. literalInt := func(expr parser.Expr) (int, bool) {
  4162. literal, ok := expr.(*parser.LiteralExpr)
  4163. if !ok || literal.Type != lexer.TokenNumber {
  4164. return 0, false
  4165. }
  4166. n, err := strconv.Atoi(literal.Value)
  4167. return n, err == nil && n >= 0
  4168. }
  4169. limit, ok := literalInt(stmt.Limit)
  4170. if !ok {
  4171. return 0, false
  4172. }
  4173. if limit == 0 {
  4174. return 0, true
  4175. }
  4176. if stmt.Offset != nil {
  4177. offset, valid := literalInt(stmt.Offset)
  4178. if !valid || offset > int(^uint(0)>>1)-limit {
  4179. return 0, false
  4180. }
  4181. limit += offset
  4182. }
  4183. return limit, true
  4184. }
  4185. func (e *Executor) extractSelectLookupCondition(expr parser.Expr, table parser.TableRef) (string, interface{}, bool) {
  4186. for join := table.Join; join != nil; join = join.Table.Join {
  4187. if join.Type == parser.JoinRight || join.Type == parser.JoinFull {
  4188. return "", nil, false
  4189. }
  4190. }
  4191. bin, ok := expr.(*parser.BinaryExpr)
  4192. if !ok {
  4193. return "", nil, false
  4194. }
  4195. copyExpr := *bin
  4196. for _, side := range []*parser.Expr{&copyExpr.Left, &copyExpr.Right} {
  4197. if column, ok := (*side).(*parser.ColumnRef); ok {
  4198. if column.Table == "" && table.Join != nil {
  4199. return "", nil, false
  4200. }
  4201. qualifier := table.Alias
  4202. if qualifier == "" {
  4203. qualifier = table.Name
  4204. }
  4205. if column.Table != "" && !strings.EqualFold(column.Table, qualifier) {
  4206. return "", nil, false
  4207. }
  4208. copyColumn := *column
  4209. copyColumn.Table = ""
  4210. *side = &copyColumn
  4211. }
  4212. }
  4213. return e.extractIndexableCondition(&copyExpr)
  4214. }
  4215. // Numeric strings can compare equal to differently formatted primary keys;
  4216. // a direct durable-key lookup would miss them. Keep those comparisons on the
  4217. // scan path until primary-key affinity has a canonical storage representation.
  4218. func safePrimaryKeyLiteral(value interface{}) bool {
  4219. if value == nil {
  4220. return false
  4221. }
  4222. if text, ok := value.(string); ok {
  4223. _, numeric := toNumeric(text)
  4224. return !numeric
  4225. }
  4226. return true
  4227. }
  4228. // executePragma executes a PRAGMA statement.
  4229. func (e *Executor) executePragma(stmt *parser.PragmaStmt) (*Result, error) {
  4230. switch stmt.Name {
  4231. case "table_info":
  4232. return e.pragmaTableInfo(stmt.Arg)
  4233. case "table_list":
  4234. return e.pragmaTableList()
  4235. case "database_list":
  4236. return e.pragmaDatabaseList()
  4237. case "version":
  4238. return e.pragmaVersion()
  4239. case "foreign_keys":
  4240. result := NewResult("PRAGMA")
  4241. if stmt.Value == nil {
  4242. result.AddColumn("foreign_keys")
  4243. result.AddRow(int64(0))
  4244. return result, nil
  4245. }
  4246. if ref, ok := stmt.Value.(*parser.ColumnRef); ok && strings.EqualFold(ref.Column, "off") {
  4247. return result, nil
  4248. }
  4249. if literal, ok := stmt.Value.(*parser.LiteralExpr); ok && literal.Value == "0" {
  4250. return result, nil
  4251. }
  4252. return nil, fmt.Errorf("PizzaSQL does not enforce foreign keys; only PRAGMA foreign_keys = OFF is supported")
  4253. default:
  4254. return nil, fmt.Errorf("unknown pragma: %s", stmt.Name)
  4255. }
  4256. }
  4257. // pragmaTableInfo returns column information for a table.
  4258. func (e *Executor) pragmaTableInfo(tableName string) (*Result, error) {
  4259. if tableName == "" {
  4260. return nil, fmt.Errorf("table_info requires a table name")
  4261. }
  4262. schema, err := e.schema.GetSchema(tableName)
  4263. if err != nil {
  4264. return nil, err
  4265. }
  4266. result := NewResult("PRAGMA")
  4267. result.AddColumn("cid")
  4268. result.AddColumn("name")
  4269. result.AddColumn("type")
  4270. result.AddColumn("notnull")
  4271. result.AddColumn("dflt_value")
  4272. result.AddColumn("pk")
  4273. for i, col := range schema.Columns {
  4274. notnull := 0
  4275. if !col.Nullable {
  4276. notnull = 1
  4277. }
  4278. pk := 0
  4279. if col.PrimaryKey {
  4280. pk = 1
  4281. }
  4282. result.AddRow(int64(i), col.Name, col.Type, int64(notnull), col.Default, int64(pk))
  4283. }
  4284. return result, nil
  4285. }
  4286. // pragmaTableList returns a list of all tables.
  4287. func (e *Executor) pragmaTableList() (*Result, error) {
  4288. tables, err := e.schema.ListTables()
  4289. if err != nil {
  4290. return nil, err
  4291. }
  4292. result := NewResult("PRAGMA")
  4293. result.AddColumn("schema")
  4294. result.AddColumn("name")
  4295. result.AddColumn("type")
  4296. for _, t := range tables {
  4297. result.AddRow("main", t, "table")
  4298. }
  4299. return result, nil
  4300. }
  4301. // pragmaDatabaseList returns a list of databases.
  4302. func (e *Executor) pragmaDatabaseList() (*Result, error) {
  4303. result := NewResult("PRAGMA")
  4304. result.AddColumn("seq")
  4305. result.AddColumn("name")
  4306. result.AddColumn("file")
  4307. // We only have one database
  4308. result.AddRow(int64(0), "main", "")
  4309. return result, nil
  4310. }
  4311. // pragmaVersion returns the PizzaSQL version.
  4312. func (e *Executor) pragmaVersion() (*Result, error) {
  4313. result := NewResult("PRAGMA")
  4314. result.AddColumn("version")
  4315. result.AddRow(version.String())
  4316. return result, nil
  4317. }
  4318. // executeExplain executes an EXPLAIN statement.
  4319. // executeAnalyze accepts ANALYZE as a documented no-op. PizzaSQL has no
  4320. // cost-based optimizer or persisted statistics, so there is nothing to gather;
  4321. // the statement exists so SQLite migrations that end with ANALYZE succeed.
  4322. func (e *Executor) executeAnalyze(stmt *parser.AnalyzeStmt) (*Result, error) {
  4323. return NewResult("ANALYZE"), nil
  4324. }
  4325. func (e *Executor) executeExplain(stmt *parser.ExplainStmt) (*Result, error) {
  4326. result := NewResult("EXPLAIN")
  4327. if stmt.QueryPlan {
  4328. // EXPLAIN QUERY PLAN format
  4329. result.AddColumn("id")
  4330. result.AddColumn("parent")
  4331. result.AddColumn("notused")
  4332. result.AddColumn("detail")
  4333. plan := e.generateQueryPlan(stmt.Statement)
  4334. for i, step := range plan {
  4335. result.AddRow(int64(i), int64(0), int64(0), step)
  4336. }
  4337. } else {
  4338. // Simple EXPLAIN format
  4339. result.AddColumn("addr")
  4340. result.AddColumn("opcode")
  4341. result.AddColumn("p1")
  4342. result.AddColumn("p2")
  4343. result.AddColumn("p3")
  4344. result.AddColumn("p4")
  4345. result.AddColumn("p5")
  4346. result.AddColumn("comment")
  4347. ops := e.generateOpcodes(stmt.Statement)
  4348. for i, op := range ops {
  4349. result.AddRow(int64(i), op, int64(0), int64(0), int64(0), "", int64(0), "")
  4350. }
  4351. }
  4352. return result, nil
  4353. }
  4354. // generateQueryPlan generates a simple query plan description.
  4355. func (e *Executor) generateQueryPlan(stmt parser.Statement) []string {
  4356. var plan []string
  4357. switch s := stmt.(type) {
  4358. case *parser.SelectStmt:
  4359. if len(s.From) > 0 {
  4360. plan = append(plan, fmt.Sprintf("SCAN TABLE %s", s.From[0].Name))
  4361. if s.Where != nil {
  4362. plan = append(plan, "FILTER")
  4363. }
  4364. if len(s.OrderBy) > 0 {
  4365. plan = append(plan, "SORT")
  4366. }
  4367. if s.Limit != nil {
  4368. plan = append(plan, "LIMIT")
  4369. }
  4370. } else {
  4371. plan = append(plan, "SCALAR EXPRESSION")
  4372. }
  4373. case *parser.InsertStmt:
  4374. plan = append(plan, fmt.Sprintf("INSERT INTO %s", s.Table.Name))
  4375. case *parser.UpdateStmt:
  4376. plan = append(plan, fmt.Sprintf("SCAN TABLE %s", s.Table.Name))
  4377. plan = append(plan, "UPDATE")
  4378. case *parser.DeleteStmt:
  4379. plan = append(plan, fmt.Sprintf("SCAN TABLE %s", s.Table.Name))
  4380. plan = append(plan, "DELETE")
  4381. default:
  4382. plan = append(plan, "EXECUTE")
  4383. }
  4384. return plan
  4385. }
  4386. // generateOpcodes generates simplified opcodes for EXPLAIN.
  4387. func (e *Executor) generateOpcodes(stmt parser.Statement) []string {
  4388. var ops []string
  4389. switch s := stmt.(type) {
  4390. case *parser.SelectStmt:
  4391. ops = append(ops, "Init")
  4392. if len(s.From) > 0 {
  4393. ops = append(ops, "OpenRead")
  4394. ops = append(ops, "Rewind")
  4395. ops = append(ops, "Column")
  4396. ops = append(ops, "ResultRow")
  4397. ops = append(ops, "Next")
  4398. ops = append(ops, "Close")
  4399. } else {
  4400. ops = append(ops, "Integer")
  4401. ops = append(ops, "ResultRow")
  4402. }
  4403. ops = append(ops, "Halt")
  4404. case *parser.InsertStmt:
  4405. ops = append(ops, "Init")
  4406. ops = append(ops, "OpenWrite")
  4407. ops = append(ops, "NewRowid")
  4408. ops = append(ops, "Insert")
  4409. ops = append(ops, "Close")
  4410. ops = append(ops, "Halt")
  4411. case *parser.UpdateStmt:
  4412. ops = append(ops, "Init")
  4413. ops = append(ops, "OpenWrite")
  4414. ops = append(ops, "Rewind")
  4415. ops = append(ops, "Column")
  4416. ops = append(ops, "Update")
  4417. ops = append(ops, "Next")
  4418. ops = append(ops, "Close")
  4419. ops = append(ops, "Halt")
  4420. case *parser.DeleteStmt:
  4421. ops = append(ops, "Init")
  4422. ops = append(ops, "OpenWrite")
  4423. ops = append(ops, "Rewind")
  4424. ops = append(ops, "Delete")
  4425. ops = append(ops, "Next")
  4426. ops = append(ops, "Close")
  4427. ops = append(ops, "Halt")
  4428. default:
  4429. ops = append(ops, "Init")
  4430. ops = append(ops, "Halt")
  4431. }
  4432. return ops
  4433. }
  4434. // evalExpr evaluates an expression.
  4435. func (e *Executor) evalExpr(expr parser.Expr, row storage.Row) (interface{}, error) {
  4436. if expr == nil {
  4437. return nil, nil
  4438. }
  4439. switch ex := expr.(type) {
  4440. case *parser.LiteralExpr:
  4441. return e.evalLiteral(ex)
  4442. case *parser.ColumnRef:
  4443. return e.evalColumnRef(ex, row)
  4444. case *parser.BinaryExpr:
  4445. return e.evalBinaryExpr(ex, row)
  4446. case *parser.UnaryExpr:
  4447. return e.evalUnaryExpr(ex, row)
  4448. case *parser.FunctionCall:
  4449. return e.evalFunctionCall(ex, row)
  4450. case *parser.ParenExpr:
  4451. return e.evalExpr(ex.Expr, row)
  4452. case *parser.CaseExpr:
  4453. return e.evalCaseExpr(ex, row)
  4454. case *parser.InExpr:
  4455. return e.evalInExpr(ex, row)
  4456. case *parser.BetweenExpr:
  4457. return e.evalBetweenExpr(ex, row)
  4458. case *parser.LikeExpr:
  4459. return e.evalLikeExpr(ex, row)
  4460. case *parser.IsNullExpr:
  4461. return e.evalIsNullExpr(ex, row)
  4462. case *parser.IsDistinctExpr:
  4463. return e.evalIsDistinctExpr(ex, row)
  4464. case *parser.CastExpr:
  4465. return e.evalCastExpr(ex, row)
  4466. case *parser.SubqueryExpr:
  4467. return e.evalSubqueryExpr(ex, row)
  4468. case *parser.ExistsExpr:
  4469. return e.evalExistsExpr(ex, row)
  4470. default:
  4471. return nil, fmt.Errorf("unsupported expression type: %T", expr)
  4472. }
  4473. }
  4474. func (e *Executor) evalLiteral(lit *parser.LiteralExpr) (interface{}, error) {
  4475. switch lit.Type {
  4476. case lexer.TokenNumber:
  4477. // Check for scientific notation (e.g., 1e+06) or decimal point
  4478. if strings.Contains(lit.Value, ".") || strings.ContainsAny(lit.Value, "eE") {
  4479. f, err := strconv.ParseFloat(lit.Value, 64)
  4480. if err != nil {
  4481. return nil, err
  4482. }
  4483. // If it's a whole number (no fractional part), return as int64
  4484. if f == float64(int64(f)) {
  4485. return int64(f), nil
  4486. }
  4487. return f, nil
  4488. }
  4489. return strconv.ParseInt(lit.Value, 10, 64)
  4490. case lexer.TokenString:
  4491. return lit.Value, nil
  4492. case lexer.TokenBlob:
  4493. // The lexer stores the decoded bytes in the literal, so a blob literal
  4494. // becomes a true []byte value.
  4495. return []byte(lit.Value), nil
  4496. case lexer.TokenNULL:
  4497. return nil, nil
  4498. case lexer.TokenTRUE:
  4499. return true, nil
  4500. case lexer.TokenFALSE:
  4501. return false, nil
  4502. default:
  4503. return lit.Value, nil
  4504. }
  4505. }
  4506. func (e *Executor) evalColumnRef(ref *parser.ColumnRef, row storage.Row) (interface{}, error) {
  4507. // SQLite date/time keywords (CURRENT_TIMESTAMP, CURRENT_DATE, CURRENT_TIME)
  4508. // are lexed as identifiers; resolve them when no real column shadows them.
  4509. if ref.Table == "" {
  4510. if _, has := lookupRowValue(row, ref.Column); !has {
  4511. if val, ok := sqliteCurrentTimeValue(ref.Column); ok {
  4512. return val, nil
  4513. }
  4514. }
  4515. }
  4516. if row == nil {
  4517. return nil, fmt.Errorf("no row context for column: %s", ref.Column)
  4518. }
  4519. // For qualified column references (table.column):
  4520. //
  4521. // Resolution order:
  4522. // 1. Exact qualified key in outer row ("t1.b" → outer)
  4523. // 2. Case-insensitive qualified in outer row
  4524. // 3. Exact qualified key in current row ("x.b" → inner alias)
  4525. // 4. Case-insensitive qualified in current row
  4526. // 5. Unqualified in outer row — only reached when qualified lookup in current
  4527. // row failed, meaning the qualifier refers to an outer table not the inner
  4528. // alias (e.g. "t1.b" in a subquery "FROM t1 AS x" resolves here).
  4529. // 6. Unqualified in current row (last resort)
  4530. if ref.Table != "" {
  4531. if e.outerRow != nil {
  4532. // Step 1-2: qualified lookup in outer row
  4533. if val, ok := e.outerRow[ref.Table+"."+ref.Column]; ok {
  4534. return val, nil
  4535. }
  4536. for k, v := range e.outerRow {
  4537. if strings.EqualFold(k, ref.Table+"."+ref.Column) {
  4538. return v, nil
  4539. }
  4540. }
  4541. }
  4542. // Step 3-4: qualified lookup in current row
  4543. if val, ok := row[ref.Table+"."+ref.Column]; ok {
  4544. return val, nil
  4545. }
  4546. for k, v := range row {
  4547. if strings.EqualFold(k, ref.Table+"."+ref.Column) {
  4548. return v, nil
  4549. }
  4550. }
  4551. // Step 5: qualified lookup failed in current row — try outer row unqualified.
  4552. // This handles correlated subqueries where the qualifier names an outer table
  4553. // (e.g. "t1.b" when the inner FROM is "t1 AS x", so current row has "x.b"
  4554. // but no "t1.b").
  4555. if e.outerRow != nil {
  4556. if val, ok := e.outerRow[ref.Column]; ok {
  4557. return val, nil
  4558. }
  4559. for k, v := range e.outerRow {
  4560. if strings.EqualFold(k, ref.Column) {
  4561. return v, nil
  4562. }
  4563. }
  4564. }
  4565. }
  4566. // Step 6: unqualified fallback in current row (handles unqualified refs and
  4567. // single-table queries like "SELECT t1.a FROM t1" where rows have plain keys).
  4568. if val, ok := row[ref.Column]; ok {
  4569. return val, nil
  4570. }
  4571. for k, v := range row {
  4572. if strings.EqualFold(k, ref.Column) {
  4573. return v, nil
  4574. }
  4575. }
  4576. // For unqualified refs with an outer row context (ref.Table == "").
  4577. if e.outerRow != nil && ref.Table == "" {
  4578. if val, ok := e.outerRow[ref.Column]; ok {
  4579. return val, nil
  4580. }
  4581. for k, v := range e.outerRow {
  4582. if strings.EqualFold(k, ref.Column) {
  4583. return v, nil
  4584. }
  4585. }
  4586. }
  4587. // Hidden rowid alias (rowid/oid/_rowid_): only used when the row carries no
  4588. // real column of that name. SQLite semantics give an explicit column named
  4589. // oid/rowid/_rowid_ precedence over the hidden rowid alias, so this fallback
  4590. // runs last.
  4591. if storage.IsRowIDColumn(ref.Column) {
  4592. if val, ok := row["_rowid_"]; ok {
  4593. return val, nil
  4594. }
  4595. }
  4596. return nil, nil // Column not found, return NULL
  4597. }
  4598. func (e *Executor) evalBinaryExpr(expr *parser.BinaryExpr, row storage.Row) (interface{}, error) {
  4599. left, err := e.evalExpr(expr.Left, row)
  4600. if err != nil {
  4601. return nil, err
  4602. }
  4603. right, err := e.evalExpr(expr.Right, row)
  4604. if err != nil {
  4605. return nil, err
  4606. }
  4607. if isBitwiseOp(expr.Op) {
  4608. if left == nil || right == nil {
  4609. return nil, nil
  4610. }
  4611. return applyBitwise(expr.Op, left, right)
  4612. }
  4613. switch expr.Op {
  4614. case lexer.TokenPlus:
  4615. if left == nil || right == nil {
  4616. return nil, nil
  4617. }
  4618. if isIntVal(left) && isIntVal(right) {
  4619. return toInt64(left) + toInt64(right), nil
  4620. }
  4621. return toFloat(left) + toFloat(right), nil
  4622. case lexer.TokenMinus:
  4623. if left == nil || right == nil {
  4624. return nil, nil
  4625. }
  4626. if isIntVal(left) && isIntVal(right) {
  4627. return toInt64(left) - toInt64(right), nil
  4628. }
  4629. return toFloat(left) - toFloat(right), nil
  4630. case lexer.TokenStar:
  4631. if left == nil || right == nil {
  4632. return nil, nil
  4633. }
  4634. if isIntVal(left) && isIntVal(right) {
  4635. return toInt64(left) * toInt64(right), nil
  4636. }
  4637. return toFloat(left) * toFloat(right), nil
  4638. case lexer.TokenSlash:
  4639. if left == nil || right == nil {
  4640. return nil, nil
  4641. }
  4642. // Integer division when both operands are integers (truncates toward zero, matching SQLite)
  4643. if isIntVal(left) && isIntVal(right) {
  4644. ri := toInt64(right)
  4645. if ri == 0 {
  4646. return nil, nil
  4647. }
  4648. return toInt64(left) / ri, nil
  4649. }
  4650. r := toFloat(right)
  4651. if r == 0 {
  4652. return nil, nil // Division by zero returns NULL
  4653. }
  4654. return toFloat(left) / r, nil
  4655. case lexer.TokenPercent:
  4656. if left == nil || right == nil {
  4657. return nil, nil
  4658. }
  4659. if isIntVal(left) && isIntVal(right) {
  4660. ri := toInt64(right)
  4661. if ri == 0 {
  4662. return nil, nil
  4663. }
  4664. return toInt64(left) % ri, nil
  4665. }
  4666. return int64(toFloat(left)) % int64(toFloat(right)), nil
  4667. case lexer.TokenEq:
  4668. if left == nil || right == nil {
  4669. return nil, nil
  4670. }
  4671. return compare(left, right) == 0, nil
  4672. case lexer.TokenNeq:
  4673. if left == nil || right == nil {
  4674. return nil, nil
  4675. }
  4676. return compare(left, right) != 0, nil
  4677. case lexer.TokenLt:
  4678. if left == nil || right == nil {
  4679. return nil, nil
  4680. }
  4681. return compare(left, right) < 0, nil
  4682. case lexer.TokenLte:
  4683. if left == nil || right == nil {
  4684. return nil, nil
  4685. }
  4686. return compare(left, right) <= 0, nil
  4687. case lexer.TokenGt:
  4688. if left == nil || right == nil {
  4689. return nil, nil
  4690. }
  4691. return compare(left, right) > 0, nil
  4692. case lexer.TokenGte:
  4693. if left == nil || right == nil {
  4694. return nil, nil
  4695. }
  4696. return compare(left, right) >= 0, nil
  4697. case lexer.TokenAND:
  4698. // Three-value logic: FALSE AND x = FALSE; NULL AND TRUE = NULL; TRUE AND TRUE = TRUE
  4699. if left != nil && !toBool(left) {
  4700. return false, nil
  4701. }
  4702. if right != nil && !toBool(right) {
  4703. return false, nil
  4704. }
  4705. if left == nil || right == nil {
  4706. return nil, nil
  4707. }
  4708. return true, nil
  4709. case lexer.TokenOR:
  4710. // Three-value logic: TRUE OR x = TRUE; NULL OR FALSE = NULL; FALSE OR FALSE = FALSE
  4711. if left != nil && toBool(left) {
  4712. return true, nil
  4713. }
  4714. if right != nil && toBool(right) {
  4715. return true, nil
  4716. }
  4717. if left == nil || right == nil {
  4718. return nil, nil
  4719. }
  4720. return false, nil
  4721. case lexer.TokenConcat:
  4722. return toString(left) + toString(right), nil
  4723. default:
  4724. return nil, fmt.Errorf("unsupported operator: %v", expr.Op)
  4725. }
  4726. }
  4727. // applyBinaryOp applies a binary operator to two already-evaluated values.
  4728. func (e *Executor) applyBinaryOp(op lexer.TokenType, left, right interface{}) (interface{}, error) {
  4729. if isBitwiseOp(op) {
  4730. if left == nil || right == nil {
  4731. return nil, nil
  4732. }
  4733. return applyBitwise(op, left, right)
  4734. }
  4735. switch op {
  4736. case lexer.TokenPlus:
  4737. if left == nil || right == nil {
  4738. return nil, nil
  4739. }
  4740. if isIntVal(left) && isIntVal(right) {
  4741. return toInt64(left) + toInt64(right), nil
  4742. }
  4743. return toFloat(left) + toFloat(right), nil
  4744. case lexer.TokenMinus:
  4745. if left == nil || right == nil {
  4746. return nil, nil
  4747. }
  4748. if isIntVal(left) && isIntVal(right) {
  4749. return toInt64(left) - toInt64(right), nil
  4750. }
  4751. return toFloat(left) - toFloat(right), nil
  4752. case lexer.TokenStar:
  4753. if left == nil || right == nil {
  4754. return nil, nil
  4755. }
  4756. if isIntVal(left) && isIntVal(right) {
  4757. return toInt64(left) * toInt64(right), nil
  4758. }
  4759. return toFloat(left) * toFloat(right), nil
  4760. case lexer.TokenSlash:
  4761. if left == nil || right == nil {
  4762. return nil, nil
  4763. }
  4764. if isIntVal(left) && isIntVal(right) {
  4765. ri := toInt64(right)
  4766. if ri == 0 {
  4767. return nil, nil
  4768. }
  4769. return toInt64(left) / ri, nil
  4770. }
  4771. r := toFloat(right)
  4772. if r == 0 {
  4773. return nil, nil
  4774. }
  4775. return toFloat(left) / r, nil
  4776. case lexer.TokenPercent:
  4777. if left == nil || right == nil {
  4778. return nil, nil
  4779. }
  4780. if isIntVal(left) && isIntVal(right) {
  4781. ri := toInt64(right)
  4782. if ri == 0 {
  4783. return nil, nil
  4784. }
  4785. return toInt64(left) % ri, nil
  4786. }
  4787. return int64(toFloat(left)) % int64(toFloat(right)), nil
  4788. case lexer.TokenEq:
  4789. if left == nil || right == nil {
  4790. return nil, nil
  4791. }
  4792. return compare(left, right) == 0, nil
  4793. case lexer.TokenNeq:
  4794. if left == nil || right == nil {
  4795. return nil, nil
  4796. }
  4797. return compare(left, right) != 0, nil
  4798. case lexer.TokenLt:
  4799. if left == nil || right == nil {
  4800. return nil, nil
  4801. }
  4802. return compare(left, right) < 0, nil
  4803. case lexer.TokenLte:
  4804. if left == nil || right == nil {
  4805. return nil, nil
  4806. }
  4807. return compare(left, right) <= 0, nil
  4808. case lexer.TokenGt:
  4809. if left == nil || right == nil {
  4810. return nil, nil
  4811. }
  4812. return compare(left, right) > 0, nil
  4813. case lexer.TokenGte:
  4814. if left == nil || right == nil {
  4815. return nil, nil
  4816. }
  4817. return compare(left, right) >= 0, nil
  4818. case lexer.TokenAND:
  4819. if left != nil && !toBool(left) {
  4820. return false, nil
  4821. }
  4822. if right != nil && !toBool(right) {
  4823. return false, nil
  4824. }
  4825. if left == nil || right == nil {
  4826. return nil, nil
  4827. }
  4828. return true, nil
  4829. case lexer.TokenOR:
  4830. if left != nil && toBool(left) {
  4831. return true, nil
  4832. }
  4833. if right != nil && toBool(right) {
  4834. return true, nil
  4835. }
  4836. if left == nil || right == nil {
  4837. return nil, nil
  4838. }
  4839. return false, nil
  4840. case lexer.TokenConcat:
  4841. return toString(left) + toString(right), nil
  4842. default:
  4843. return nil, fmt.Errorf("unsupported operator: %v", op)
  4844. }
  4845. }
  4846. // isBitwiseOp reports whether op is a SQLite bitwise operator.
  4847. func isBitwiseOp(op lexer.TokenType) bool {
  4848. switch op {
  4849. case lexer.TokenBitAnd, lexer.TokenBitOr, lexer.TokenShiftLeft, lexer.TokenShiftRight:
  4850. return true
  4851. }
  4852. return false
  4853. }
  4854. // applyBitwise applies a bitwise operator with SQLite semantics. Operands are
  4855. // coerced to integers; a negative shift reverses direction, and an
  4856. // out-of-range shift saturates.
  4857. func applyBitwise(op lexer.TokenType, left, right interface{}) (interface{}, error) {
  4858. li := toInt64(left)
  4859. ri := toInt64(right)
  4860. switch op {
  4861. case lexer.TokenBitAnd:
  4862. return li & ri, nil
  4863. case lexer.TokenBitOr:
  4864. return li | ri, nil
  4865. case lexer.TokenShiftLeft:
  4866. return bitShiftLeft(li, ri), nil
  4867. case lexer.TokenShiftRight:
  4868. return bitShiftRight(li, ri), nil
  4869. default:
  4870. return nil, fmt.Errorf("unsupported bitwise operator: %v", op)
  4871. }
  4872. }
  4873. func bitShiftLeft(v, shift int64) int64 {
  4874. if shift < 0 {
  4875. return bitShiftRight(v, -shift)
  4876. }
  4877. if shift >= 64 {
  4878. return 0
  4879. }
  4880. return v << uint(shift)
  4881. }
  4882. func bitShiftRight(v, shift int64) int64 {
  4883. if shift < 0 {
  4884. return bitShiftLeft(v, -shift)
  4885. }
  4886. if shift >= 64 {
  4887. if v < 0 {
  4888. return -1
  4889. }
  4890. return 0
  4891. }
  4892. return v >> uint(shift)
  4893. }
  4894. // evalBuiltinFunction applies a named scalar function to pre-evaluated args.
  4895. func (e *Executor) evalBuiltinFunction(name string, args []interface{}) (interface{}, error) {
  4896. switch name {
  4897. case "NULLIF":
  4898. if len(args) >= 2 && compare(args[0], args[1]) == 0 {
  4899. return nil, nil
  4900. }
  4901. if len(args) > 0 {
  4902. return args[0], nil
  4903. }
  4904. case "IFNULL", "NVL":
  4905. if len(args) >= 2 {
  4906. if args[0] == nil {
  4907. return args[1], nil
  4908. }
  4909. return args[0], nil
  4910. }
  4911. case "COALESCE":
  4912. for _, a := range args {
  4913. if a != nil {
  4914. return a, nil
  4915. }
  4916. }
  4917. return nil, nil
  4918. case "ABS":
  4919. if len(args) > 0 && args[0] != nil {
  4920. if isIntVal(args[0]) {
  4921. v := toInt64(args[0])
  4922. if v < 0 {
  4923. return -v, nil
  4924. }
  4925. return v, nil
  4926. }
  4927. v := toFloat(args[0])
  4928. if v < 0 {
  4929. return -v, nil
  4930. }
  4931. return v, nil
  4932. }
  4933. case "LENGTH":
  4934. if len(args) > 0 && args[0] != nil {
  4935. return int64(len(fmt.Sprintf("%v", args[0]))), nil
  4936. }
  4937. }
  4938. // Fall back: store pre-evaluated values in row and build column refs.
  4939. row := make(storage.Row, len(args))
  4940. fn := &parser.FunctionCall{Name: name}
  4941. for i, a := range args {
  4942. key := fmt.Sprintf("__arg%d__", i)
  4943. row[key] = a
  4944. fn.Args = append(fn.Args, &parser.ColumnRef{Column: key})
  4945. }
  4946. return e.evalFunctionCall(fn, row)
  4947. }
  4948. func (e *Executor) evalUnaryExpr(expr *parser.UnaryExpr, row storage.Row) (interface{}, error) {
  4949. val, err := e.evalExpr(expr.Operand, row)
  4950. if err != nil {
  4951. return nil, err
  4952. }
  4953. switch expr.Op {
  4954. case lexer.TokenMinus:
  4955. if val == nil {
  4956. return nil, nil
  4957. }
  4958. if isIntVal(val) {
  4959. return -toInt64(val), nil
  4960. }
  4961. return -toFloat(val), nil
  4962. case lexer.TokenPlus:
  4963. if val == nil {
  4964. return nil, nil
  4965. }
  4966. if isIntVal(val) {
  4967. return toInt64(val), nil
  4968. }
  4969. return toFloat(val), nil
  4970. case lexer.TokenNOT:
  4971. if val == nil {
  4972. return nil, nil // NOT NULL = NULL
  4973. }
  4974. return !toBool(val), nil
  4975. case lexer.TokenBitNot:
  4976. if val == nil {
  4977. return nil, nil
  4978. }
  4979. return ^toInt64(val), nil
  4980. default:
  4981. return val, nil
  4982. }
  4983. }
  4984. func (e *Executor) evalFunctionCall(fn *parser.FunctionCall, row storage.Row) (interface{}, error) {
  4985. name := strings.ToUpper(fn.Name)
  4986. // Evaluate arguments
  4987. args := make([]interface{}, len(fn.Args))
  4988. for i, arg := range fn.Args {
  4989. val, err := e.evalExpr(arg, row)
  4990. if err != nil {
  4991. return nil, err
  4992. }
  4993. args[i] = val
  4994. }
  4995. // JSON1 scalar functions are dispatched separately to keep this switch tidy.
  4996. if val, handled, err := evalJSONFunction(name, args); handled {
  4997. return val, err
  4998. }
  4999. switch name {
  5000. case "UPPER":
  5001. if len(args) > 0 {
  5002. if args[0] == nil {
  5003. return nil, nil // NULL propagation
  5004. }
  5005. return strings.ToUpper(toString(args[0])), nil
  5006. }
  5007. case "LOWER":
  5008. if len(args) > 0 {
  5009. if args[0] == nil {
  5010. return nil, nil // NULL propagation
  5011. }
  5012. return strings.ToLower(toString(args[0])), nil
  5013. }
  5014. case "LENGTH":
  5015. if len(args) > 0 {
  5016. if args[0] == nil {
  5017. return nil, nil // NULL propagation
  5018. }
  5019. return int64(len(toString(args[0]))), nil
  5020. }
  5021. case "ABS":
  5022. if len(args) > 0 {
  5023. if args[0] == nil {
  5024. return nil, nil
  5025. }
  5026. v := toFloat(args[0])
  5027. if v < 0 {
  5028. return -v, nil
  5029. }
  5030. return v, nil
  5031. }
  5032. case "COALESCE":
  5033. for _, arg := range args {
  5034. if arg != nil {
  5035. return arg, nil
  5036. }
  5037. }
  5038. return nil, nil
  5039. case "NULLIF":
  5040. if len(args) >= 2 && compare(args[0], args[1]) == 0 {
  5041. return nil, nil
  5042. }
  5043. if len(args) > 0 {
  5044. return args[0], nil
  5045. }
  5046. case "IFNULL":
  5047. if len(args) >= 2 {
  5048. if args[0] == nil {
  5049. return args[1], nil
  5050. }
  5051. return args[0], nil
  5052. }
  5053. case "TYPEOF":
  5054. if len(args) > 0 {
  5055. switch args[0].(type) {
  5056. case nil:
  5057. return "null", nil
  5058. case int64, int:
  5059. return "integer", nil
  5060. case float64:
  5061. return "real", nil
  5062. case string:
  5063. return "text", nil
  5064. case []byte:
  5065. return "blob", nil
  5066. default:
  5067. return "text", nil
  5068. }
  5069. }
  5070. case "SUBSTR", "SUBSTRING":
  5071. if len(args) >= 2 {
  5072. // SQLite substring semantics. Indices are 1-based and inclusive:
  5073. // a zero or negative Y shifts the window rather than simply
  5074. // clamping, e.g. substr('US-NY', 0, 3) is 'US', not 'US-'.
  5075. runes := []rune(toString(args[0]))
  5076. n := len(runes)
  5077. y := int(toFloat(args[1]))
  5078. var start1, end1 int
  5079. switch {
  5080. case y < 0:
  5081. start1 = n + y + 1
  5082. case y == 0:
  5083. start1 = 1
  5084. default:
  5085. start1 = y
  5086. }
  5087. if len(args) >= 3 {
  5088. z := int(toFloat(args[2]))
  5089. switch {
  5090. case z < 0:
  5091. end1 = start1 - 1
  5092. start1 = end1 + z + 1
  5093. case y < 0:
  5094. end1 = start1 + z - 1
  5095. case y == 0:
  5096. end1 = z - 1
  5097. default:
  5098. end1 = y + z - 1
  5099. }
  5100. } else {
  5101. end1 = n
  5102. }
  5103. if start1 < 1 {
  5104. start1 = 1
  5105. }
  5106. if end1 > n {
  5107. end1 = n
  5108. }
  5109. if start1 > n || start1 > end1 {
  5110. return "", nil
  5111. }
  5112. return string(runes[start1-1 : end1]), nil
  5113. }
  5114. case "TRIM":
  5115. if len(args) > 0 {
  5116. return strings.TrimSpace(toString(args[0])), nil
  5117. }
  5118. case "REPLACE":
  5119. if len(args) >= 3 {
  5120. return strings.ReplaceAll(toString(args[0]), toString(args[1]), toString(args[2])), nil
  5121. }
  5122. // Additional SQLite functions
  5123. case "PRINTF":
  5124. if len(args) > 0 {
  5125. format := toString(args[0])
  5126. fmtArgs := make([]interface{}, len(args)-1)
  5127. for i := 1; i < len(args); i++ {
  5128. fmtArgs[i-1] = args[i]
  5129. }
  5130. return fmt.Sprintf(format, fmtArgs...), nil
  5131. }
  5132. case "HEX":
  5133. if len(args) > 0 {
  5134. if args[0] == nil {
  5135. return nil, nil
  5136. }
  5137. if b, ok := args[0].([]byte); ok {
  5138. return strings.ToUpper(fmt.Sprintf("%x", b)), nil
  5139. }
  5140. return strings.ToUpper(fmt.Sprintf("%x", []byte(toString(args[0])))), nil
  5141. }
  5142. case "UNHEX":
  5143. if len(args) > 0 {
  5144. if args[0] == nil {
  5145. return nil, nil
  5146. }
  5147. s := toString(args[0])
  5148. result, err := hex.DecodeString(strings.TrimSpace(s))
  5149. if err != nil {
  5150. return nil, nil
  5151. }
  5152. return result, nil
  5153. }
  5154. case "RANDOM":
  5155. return rand.Int63(), nil
  5156. case "RANDOMBLOB":
  5157. if len(args) > 0 {
  5158. n := int(toFloat(args[0]))
  5159. if n <= 0 {
  5160. n = 1
  5161. }
  5162. if n > 1000000 {
  5163. n = 1000000
  5164. }
  5165. blob := make([]byte, n)
  5166. rand.Read(blob)
  5167. return blob, nil
  5168. }
  5169. case "ZEROBLOB":
  5170. if len(args) > 0 {
  5171. n := int(toFloat(args[0]))
  5172. if n <= 0 {
  5173. n = 1
  5174. }
  5175. if n > 1000000 {
  5176. n = 1000000
  5177. }
  5178. return make([]byte, n), nil
  5179. }
  5180. case "INSTR":
  5181. if len(args) >= 2 {
  5182. s := toString(args[0])
  5183. substr := toString(args[1])
  5184. idx := strings.Index(s, substr)
  5185. if idx < 0 {
  5186. return int64(0), nil
  5187. }
  5188. return int64(idx + 1), nil // SQL is 1-indexed
  5189. }
  5190. case "GLOB":
  5191. if len(args) >= 2 {
  5192. pattern := toString(args[0])
  5193. s := toString(args[1])
  5194. return matchGlob(pattern, s), nil
  5195. }
  5196. case "ROUND":
  5197. if len(args) > 0 {
  5198. v := toFloat(args[0])
  5199. decimals := 0
  5200. if len(args) >= 2 {
  5201. decimals = int(toFloat(args[1]))
  5202. }
  5203. mult := 1.0
  5204. for i := 0; i < decimals; i++ {
  5205. mult *= 10
  5206. }
  5207. return float64(int64(v*mult+0.5)) / mult, nil
  5208. }
  5209. case "MAX":
  5210. if len(args) > 0 {
  5211. max := args[0]
  5212. for _, arg := range args[1:] {
  5213. if compare(arg, max) > 0 {
  5214. max = arg
  5215. }
  5216. }
  5217. return max, nil
  5218. }
  5219. case "MIN":
  5220. if len(args) > 0 {
  5221. min := args[0]
  5222. for _, arg := range args[1:] {
  5223. if compare(arg, min) < 0 {
  5224. min = arg
  5225. }
  5226. }
  5227. return min, nil
  5228. }
  5229. case "CONCAT":
  5230. var result strings.Builder
  5231. for _, arg := range args {
  5232. result.WriteString(toString(arg))
  5233. }
  5234. return result.String(), nil
  5235. case "CONCAT_WS":
  5236. // PostgreSQL semantics: a NULL separator yields NULL; NULL arguments are
  5237. // skipped rather than converted to empty strings.
  5238. if len(args) == 0 || args[0] == nil {
  5239. return nil, nil
  5240. }
  5241. separator := toString(args[0])
  5242. parts := make([]string, 0, len(args)-1)
  5243. for _, arg := range args[1:] {
  5244. if arg != nil {
  5245. parts = append(parts, toString(arg))
  5246. }
  5247. }
  5248. return strings.Join(parts, separator), nil
  5249. // Date/Time functions
  5250. case "DATE":
  5251. return evalDateFunc(args)
  5252. case "TIME":
  5253. return evalTimeFunc(args)
  5254. case "DATETIME":
  5255. return evalDatetimeFunc(args)
  5256. case "JULIANDAY":
  5257. return evalJuliandayFunc(args)
  5258. case "UNIXEPOCH":
  5259. return evalUnixepochFunc(args)
  5260. case "STRFTIME":
  5261. return evalStrftimeFunc(args)
  5262. case "TIMEDIFF":
  5263. return evalTimediffFunc(args)
  5264. case "PERCENT_DIFF":
  5265. return evalPercentDiff(args)
  5266. case "PIZZASQL_VERSION":
  5267. return version.String(), nil
  5268. case "SQLITE_VERSION":
  5269. return SQLiteCompatVersion, nil
  5270. case "LAST_INSERT_ROWID":
  5271. return e.lastInsertRowID, nil
  5272. case "PG_BACKEND_PID":
  5273. return int64(e.backendPID), nil
  5274. case "CHANGES":
  5275. return e.changes, nil
  5276. case "TOTAL_CHANGES":
  5277. return e.totalChanges, nil
  5278. }
  5279. return nil, nil
  5280. }
  5281. func (e *Executor) evalCaseExpr(expr *parser.CaseExpr, row storage.Row) (interface{}, error) {
  5282. var operand interface{}
  5283. if expr.Operand != nil {
  5284. var err error
  5285. operand, err = e.evalExpr(expr.Operand, row)
  5286. if err != nil {
  5287. return nil, err
  5288. }
  5289. }
  5290. for _, when := range expr.Whens {
  5291. cond, err := e.evalExpr(when.Condition, row)
  5292. if err != nil {
  5293. return nil, err
  5294. }
  5295. var match bool
  5296. if expr.Operand != nil {
  5297. // Simple CASE: CASE operand WHEN val THEN ... — NULL operand matches nothing
  5298. if operand == nil {
  5299. continue
  5300. }
  5301. match = compare(operand, cond) == 0
  5302. } else {
  5303. // Searched CASE: CASE WHEN cond THEN ... — NULL condition is falsy
  5304. match = toBool(cond)
  5305. }
  5306. if match {
  5307. return e.evalExpr(when.Result, row)
  5308. }
  5309. }
  5310. if expr.Else != nil {
  5311. return e.evalExpr(expr.Else, row)
  5312. }
  5313. return nil, nil
  5314. }
  5315. func (e *Executor) evalInExpr(expr *parser.InExpr, row storage.Row) (interface{}, error) {
  5316. left, err := e.evalExpr(expr.Left, row)
  5317. if err != nil {
  5318. return nil, err
  5319. }
  5320. // Handle subquery: IN (SELECT ...)
  5321. if expr.Subquery != nil {
  5322. var result *Result
  5323. var err error
  5324. // Cache non-correlated subquery results for the duration of this query.
  5325. // Safe when outerRow is nil (no outer context that the subquery could reference).
  5326. if e.subqueryCache != nil && e.outerRow == nil {
  5327. if cached, ok := e.subqueryCache[expr.Subquery]; ok {
  5328. result = cached
  5329. } else {
  5330. result, err = e.executeSelect(expr.Subquery)
  5331. if err == nil {
  5332. e.subqueryCache[expr.Subquery] = result
  5333. }
  5334. }
  5335. } else {
  5336. result, err = e.executeSelect(expr.Subquery)
  5337. }
  5338. if err != nil {
  5339. return nil, fmt.Errorf("IN subquery error: %w", err)
  5340. }
  5341. if len(result.Columns) != 1 {
  5342. return nil, fmt.Errorf("subquery in IN must return exactly one column")
  5343. }
  5344. // SQL three-valued logic: if left is NULL → NULL; if any match → true; if any NULL → NULL; else false.
  5345. if left == nil {
  5346. return nil, nil
  5347. }
  5348. sawNull := false
  5349. for _, resultRow := range result.Rows {
  5350. if len(resultRow) == 0 {
  5351. continue
  5352. }
  5353. v := resultRow[0]
  5354. if v == nil {
  5355. sawNull = true
  5356. continue
  5357. }
  5358. if compare(left, v) == 0 {
  5359. if expr.Not {
  5360. return false, nil
  5361. }
  5362. return true, nil
  5363. }
  5364. }
  5365. if sawNull {
  5366. return nil, nil
  5367. }
  5368. if expr.Not {
  5369. return true, nil
  5370. }
  5371. return false, nil
  5372. }
  5373. // Handle value list: IN (1, 2, 3).
  5374. // Empty list: always FALSE (IN) / TRUE (NOT IN), even for NULL.
  5375. if len(expr.Values) == 0 {
  5376. return expr.Not, nil
  5377. }
  5378. // SQL three-valued logic: if left is NULL → NULL; if any match → true/false;
  5379. // if list contains NULL and no match → NULL.
  5380. if left == nil {
  5381. return nil, nil
  5382. }
  5383. sawNull := false
  5384. for _, val := range expr.Values {
  5385. v, err := e.evalExpr(val, row)
  5386. if err != nil {
  5387. return nil, err
  5388. }
  5389. if v == nil {
  5390. sawNull = true
  5391. continue
  5392. }
  5393. if compare(left, v) == 0 {
  5394. if expr.Not {
  5395. return false, nil
  5396. }
  5397. return true, nil
  5398. }
  5399. }
  5400. if sawNull {
  5401. return nil, nil
  5402. }
  5403. if expr.Not {
  5404. return true, nil
  5405. }
  5406. return false, nil
  5407. }
  5408. func (e *Executor) evalBetweenExpr(expr *parser.BetweenExpr, row storage.Row) (interface{}, error) {
  5409. val, err := e.evalExpr(expr.Left, row)
  5410. if err != nil {
  5411. return nil, err
  5412. }
  5413. low, err := e.evalExpr(expr.Low, row)
  5414. if err != nil {
  5415. return nil, err
  5416. }
  5417. high, err := e.evalExpr(expr.High, row)
  5418. if err != nil {
  5419. return nil, err
  5420. }
  5421. if expr.Not {
  5422. // NOT BETWEEN is equivalent to: val < low OR val > high
  5423. // We need to handle NULL using three-valued OR logic:
  5424. // NULL OR TRUE = TRUE
  5425. // NULL OR FALSE = NULL
  5426. // NULL OR NULL = NULL
  5427. var lessThan, greaterThan interface{}
  5428. if val == nil || low == nil {
  5429. lessThan = nil // NULL
  5430. } else {
  5431. lessThan = compare(val, low) < 0
  5432. }
  5433. if val == nil || high == nil {
  5434. greaterThan = nil // NULL
  5435. } else {
  5436. greaterThan = compare(val, high) > 0
  5437. }
  5438. // Implement three-valued OR
  5439. if toBool(lessThan) || toBool(greaterThan) {
  5440. return true, nil
  5441. }
  5442. if lessThan == nil || greaterThan == nil {
  5443. return nil, nil // NULL
  5444. }
  5445. return false, nil
  5446. } else {
  5447. // BETWEEN is equivalent to: val >= low AND val <= high
  5448. // Three-value logic: if val < low → FALSE (regardless of high); if val >= low and high is NULL → NULL
  5449. if val == nil {
  5450. return nil, nil
  5451. }
  5452. // x BETWEEN a AND b = (x >= a) AND (x <= b)
  5453. // NULL AND FALSE = FALSE; NULL AND TRUE = NULL
  5454. if low == nil {
  5455. // x >= NULL = NULL; check upper bound for early FALSE
  5456. if high != nil && compare(val, high) > 0 {
  5457. return false, nil // NULL AND FALSE = FALSE
  5458. }
  5459. return nil, nil // NULL AND TRUE/NULL = NULL
  5460. }
  5461. if compare(val, low) < 0 {
  5462. return false, nil // val < low → FALSE AND anything = FALSE
  5463. }
  5464. if high == nil {
  5465. return nil, nil // TRUE AND NULL = NULL
  5466. }
  5467. return compare(val, high) <= 0, nil
  5468. }
  5469. }
  5470. func (e *Executor) evalLikeExpr(expr *parser.LikeExpr, row storage.Row) (interface{}, error) {
  5471. val, err := e.evalExpr(expr.Left, row)
  5472. if err != nil {
  5473. return nil, err
  5474. }
  5475. pattern, err := e.evalExpr(expr.Pattern, row)
  5476. if err != nil {
  5477. return nil, err
  5478. }
  5479. s := toString(val)
  5480. p := toString(pattern)
  5481. // Convert SQL LIKE pattern to simple matching
  5482. // % matches any sequence, _ matches single character
  5483. matched := matchLike(s, p)
  5484. if expr.Not {
  5485. return !matched, nil
  5486. }
  5487. return matched, nil
  5488. }
  5489. func (e *Executor) evalIsNullExpr(expr *parser.IsNullExpr, row storage.Row) (interface{}, error) {
  5490. val, err := e.evalExpr(expr.Left, row)
  5491. if err != nil {
  5492. return nil, err
  5493. }
  5494. isNull := val == nil
  5495. if expr.Not {
  5496. return !isNull, nil
  5497. }
  5498. return isNull, nil
  5499. }
  5500. // evalIsDistinctExpr implements `a IS [NOT] DISTINCT FROM b`. It treats NULL as a
  5501. // comparable value: two NULLs are not distinct, and NULL is distinct from any
  5502. // non-NULL.
  5503. func (e *Executor) evalIsDistinctExpr(expr *parser.IsDistinctExpr, row storage.Row) (interface{}, error) {
  5504. left, err := e.evalExpr(expr.Left, row)
  5505. if err != nil {
  5506. return nil, err
  5507. }
  5508. right, err := e.evalExpr(expr.Right, row)
  5509. if err != nil {
  5510. return nil, err
  5511. }
  5512. distinct := false
  5513. switch {
  5514. case left == nil && right == nil:
  5515. distinct = false
  5516. case left == nil || right == nil:
  5517. distinct = true
  5518. default:
  5519. distinct = compare(left, right) != 0
  5520. }
  5521. if expr.Not {
  5522. return !distinct, nil
  5523. }
  5524. return distinct, nil
  5525. }
  5526. func (e *Executor) evalCastExpr(expr *parser.CastExpr, row storage.Row) (interface{}, error) {
  5527. val, err := e.evalExpr(expr.Expr, row)
  5528. if err != nil {
  5529. return nil, err
  5530. }
  5531. if val == nil {
  5532. return nil, nil // CAST(NULL AS any) = NULL
  5533. }
  5534. typeName := strings.ToUpper(expr.Type.Name)
  5535. switch {
  5536. case strings.Contains(typeName, "INT"):
  5537. return int64(toFloat(val)), nil
  5538. case strings.Contains(typeName, "REAL"), strings.Contains(typeName, "FLOAT"), strings.Contains(typeName, "DOUBLE"):
  5539. return toFloat(val), nil
  5540. case strings.Contains(typeName, "BLOB"):
  5541. if b, ok := val.([]byte); ok {
  5542. return b, nil
  5543. }
  5544. return []byte(toString(val)), nil
  5545. case strings.Contains(typeName, "TEXT"), strings.Contains(typeName, "CHAR"):
  5546. return toString(val), nil
  5547. default:
  5548. return val, nil
  5549. }
  5550. }
  5551. // evalSubqueryExpr executes a scalar subquery and returns its value.
  5552. // A scalar subquery must return exactly one column. It returns:
  5553. // - The single value if the subquery returns one row
  5554. // - NULL if the subquery returns no rows
  5555. // - Error if the subquery returns more than one row (for strict SQL compliance)
  5556. func (e *Executor) evalSubqueryExpr(expr *parser.SubqueryExpr, row storage.Row) (interface{}, error) {
  5557. if row != nil && e.correlatedAggCache != nil {
  5558. if val, ok, err := e.evalDecorrelatedAggSubquery(expr.Query, row); ok || err != nil {
  5559. return val, err
  5560. }
  5561. }
  5562. // Save and set outer row context for correlated subqueries
  5563. savedOuter := e.outerRow
  5564. e.outerRow = row
  5565. defer func() { e.outerRow = savedOuter }()
  5566. // Execute the subquery
  5567. result, err := e.executeSelect(expr.Query)
  5568. if err != nil {
  5569. return nil, fmt.Errorf("subquery error: %w", err)
  5570. }
  5571. // Check for empty result
  5572. if result.RowCount == 0 {
  5573. return nil, nil // Return NULL for empty subquery
  5574. }
  5575. // Check column count
  5576. if len(result.Columns) == 0 {
  5577. return nil, fmt.Errorf("subquery must return at least one column")
  5578. }
  5579. // For scalar subquery, return first column of first row
  5580. // Note: Strict SQL would error if more than one row is returned
  5581. // but we follow SQLite behavior which just returns the first value
  5582. if len(result.Rows) > 0 && len(result.Rows[0]) > 0 {
  5583. return result.Rows[0][0], nil
  5584. }
  5585. return nil, nil
  5586. }
  5587. func (e *Executor) evalDecorrelatedAggSubquery(query *parser.SelectStmt, outerRow storage.Row) (interface{}, bool, error) {
  5588. spec, ok := e.correlatedAggSpec(query)
  5589. if !ok {
  5590. return nil, false, nil
  5591. }
  5592. outerVal, err := e.evalExpr(spec.outerKey, outerRow)
  5593. if err != nil {
  5594. return nil, true, err
  5595. }
  5596. cache, exists := e.correlatedAggCache[query]
  5597. if !exists {
  5598. cache, err = e.buildCorrelatedAggCache(query, spec)
  5599. if err != nil {
  5600. return nil, true, err
  5601. }
  5602. e.correlatedAggCache[query] = cache
  5603. }
  5604. if outerVal == nil {
  5605. return cache.defaultValue, true, nil
  5606. }
  5607. if val, exists := cache.values[fmt.Sprintf("%v", outerVal)]; exists {
  5608. return val, true, nil
  5609. }
  5610. return cache.defaultValue, true, nil
  5611. }
  5612. func (e *Executor) correlatedAggSpec(query *parser.SelectStmt) (correlatedAggSpec, bool) {
  5613. if query == nil ||
  5614. query.Compound != nil ||
  5615. len(query.Columns) != 1 ||
  5616. len(query.From) == 0 ||
  5617. query.Where == nil ||
  5618. len(query.GroupBy) > 0 ||
  5619. query.Having != nil ||
  5620. query.Limit != nil ||
  5621. query.Offset != nil {
  5622. return correlatedAggSpec{}, false
  5623. }
  5624. if query.Columns[0].Star {
  5625. return correlatedAggSpec{}, false
  5626. }
  5627. agg, ok := query.Columns[0].Expr.(*parser.FunctionCall)
  5628. if !ok {
  5629. return correlatedAggSpec{}, false
  5630. }
  5631. switch strings.ToUpper(agg.Name) {
  5632. case "COUNT", "SUM", "AVG", "MIN", "MAX":
  5633. default:
  5634. return correlatedAggSpec{}, false
  5635. }
  5636. innerAliases := collectFromAliases(query.From)
  5637. bin, ok := query.Where.(*parser.BinaryExpr)
  5638. if !ok || bin.Op != lexer.TokenEq {
  5639. return correlatedAggSpec{}, false
  5640. }
  5641. leftRef, leftIsRef := bin.Left.(*parser.ColumnRef)
  5642. rightRef, rightIsRef := bin.Right.(*parser.ColumnRef)
  5643. if !leftIsRef || !rightIsRef {
  5644. return correlatedAggSpec{}, false
  5645. }
  5646. leftInner := refBelongsToAliases(leftRef, innerAliases)
  5647. rightInner := refBelongsToAliases(rightRef, innerAliases)
  5648. if leftInner == rightInner {
  5649. return correlatedAggSpec{}, false
  5650. }
  5651. if leftInner {
  5652. return correlatedAggSpec{innerKey: leftRef, outerKey: rightRef, aggExpr: agg}, true
  5653. }
  5654. return correlatedAggSpec{innerKey: rightRef, outerKey: leftRef, aggExpr: agg}, true
  5655. }
  5656. func (e *Executor) buildCorrelatedAggCache(query *parser.SelectStmt, spec correlatedAggSpec) (*correlatedAggCache, error) {
  5657. grouped := *query
  5658. grouped.Where = nil
  5659. grouped.GroupBy = []parser.Expr{spec.innerKey}
  5660. grouped.Having = nil
  5661. grouped.OrderBy = nil
  5662. grouped.Limit = nil
  5663. grouped.Offset = nil
  5664. grouped.Columns = []parser.SelectColumn{
  5665. {Expr: spec.innerKey, Alias: "__corr_key"},
  5666. {Expr: spec.aggExpr, Alias: "__corr_value"},
  5667. }
  5668. savedOuter := e.outerRow
  5669. e.outerRow = nil
  5670. result, err := e.executeSelect(&grouped)
  5671. e.outerRow = savedOuter
  5672. if err != nil {
  5673. return nil, fmt.Errorf("decorrelated aggregate subquery error: %w", err)
  5674. }
  5675. cache := &correlatedAggCache{
  5676. values: make(map[string]interface{}, len(result.Rows)),
  5677. defaultValue: correlatedAggDefault(spec.aggExpr),
  5678. }
  5679. for _, row := range result.Rows {
  5680. if len(row) < 2 || row[0] == nil {
  5681. continue
  5682. }
  5683. cache.values[fmt.Sprintf("%v", row[0])] = row[1]
  5684. }
  5685. return cache, nil
  5686. }
  5687. func correlatedAggDefault(expr parser.Expr) interface{} {
  5688. if fn, ok := expr.(*parser.FunctionCall); ok && strings.EqualFold(fn.Name, "COUNT") {
  5689. return int64(0)
  5690. }
  5691. return nil
  5692. }
  5693. func collectFromAliases(from []parser.TableRef) map[string]struct{} {
  5694. aliases := make(map[string]struct{})
  5695. var addRef func(parser.TableRef)
  5696. addRef = func(ref parser.TableRef) {
  5697. if ref.Name != "" {
  5698. aliases[strings.ToLower(ref.Name)] = struct{}{}
  5699. }
  5700. if ref.Alias != "" {
  5701. aliases[strings.ToLower(ref.Alias)] = struct{}{}
  5702. }
  5703. if ref.Join != nil && ref.Join.Table != nil {
  5704. addRef(*ref.Join.Table)
  5705. }
  5706. }
  5707. for _, ref := range from {
  5708. addRef(ref)
  5709. }
  5710. return aliases
  5711. }
  5712. func refBelongsToAliases(ref *parser.ColumnRef, aliases map[string]struct{}) bool {
  5713. if ref == nil || ref.Table == "" {
  5714. return false
  5715. }
  5716. _, ok := aliases[strings.ToLower(ref.Table)]
  5717. return ok
  5718. }
  5719. // evalExistsExpr evaluates an EXISTS expression.
  5720. // Returns true if the subquery returns at least one row, false otherwise.
  5721. func (e *Executor) evalExistsExpr(expr *parser.ExistsExpr, row storage.Row) (interface{}, error) {
  5722. // Save and set outer row context for correlated subqueries
  5723. savedOuter := e.outerRow
  5724. e.outerRow = row
  5725. defer func() { e.outerRow = savedOuter }()
  5726. // Execute the subquery
  5727. result, err := e.executeSelect(expr.Subquery)
  5728. if err != nil {
  5729. return nil, fmt.Errorf("EXISTS subquery error: %w", err)
  5730. }
  5731. // EXISTS returns true if any rows are returned
  5732. return len(result.Rows) > 0, nil
  5733. }
  5734. // evalAggregateExpr evaluates an aggregate expression over multiple rows.
  5735. func (e *Executor) evalAggregateExpr(expr parser.Expr, rows []storage.Row) (interface{}, error) {
  5736. fn, ok := expr.(*parser.FunctionCall)
  5737. if !ok {
  5738. // Not a function call - could be a binary expression with aggregates inside
  5739. // Evaluate it with the aggregate evaluation context
  5740. return e.evalExprWithAggregates(expr, rows)
  5741. }
  5742. name := strings.ToUpper(fn.Name)
  5743. switch name {
  5744. case "COUNT":
  5745. if fn.Star {
  5746. return int64(len(rows)), nil
  5747. }
  5748. if fn.Distinct {
  5749. seen := make(map[interface{}]struct{})
  5750. for _, row := range rows {
  5751. if len(fn.Args) > 0 {
  5752. val, _ := e.evalExpr(fn.Args[0], row)
  5753. if val != nil {
  5754. seen[val] = struct{}{}
  5755. }
  5756. }
  5757. }
  5758. return int64(len(seen)), nil
  5759. }
  5760. count := int64(0)
  5761. for _, row := range rows {
  5762. if len(fn.Args) > 0 {
  5763. val, _ := e.evalExpr(fn.Args[0], row)
  5764. if val != nil {
  5765. count++
  5766. }
  5767. }
  5768. }
  5769. return count, nil
  5770. case "SUM":
  5771. var sumInt int64
  5772. var sumFloat float64
  5773. allInt := true
  5774. hasValues := false
  5775. var seen map[interface{}]struct{}
  5776. if fn.Distinct {
  5777. seen = make(map[interface{}]struct{})
  5778. }
  5779. for _, row := range rows {
  5780. if len(fn.Args) > 0 {
  5781. val, _ := e.evalExpr(fn.Args[0], row)
  5782. if val != nil {
  5783. if fn.Distinct {
  5784. key := fmt.Sprintf("%v", val)
  5785. if _, exists := seen[key]; exists {
  5786. continue
  5787. }
  5788. seen[key] = struct{}{}
  5789. }
  5790. if isIntVal(val) {
  5791. sumInt += toInt64(val)
  5792. } else {
  5793. allInt = false
  5794. sumFloat += toFloat(val)
  5795. }
  5796. hasValues = true
  5797. }
  5798. }
  5799. }
  5800. if !hasValues {
  5801. return nil, nil
  5802. }
  5803. if allInt {
  5804. return sumInt, nil
  5805. }
  5806. return sumFloat + float64(sumInt), nil
  5807. case "AVG":
  5808. var sum float64
  5809. count := 0
  5810. for _, row := range rows {
  5811. if len(fn.Args) > 0 {
  5812. val, _ := e.evalExpr(fn.Args[0], row)
  5813. if val != nil {
  5814. sum += toFloat(val)
  5815. count++
  5816. }
  5817. }
  5818. }
  5819. if count == 0 {
  5820. return nil, nil
  5821. }
  5822. return sum / float64(count), nil
  5823. case "MIN":
  5824. var min interface{}
  5825. for _, row := range rows {
  5826. if len(fn.Args) > 0 {
  5827. val, _ := e.evalExpr(fn.Args[0], row)
  5828. if val != nil && (min == nil || compare(val, min) < 0) {
  5829. min = val
  5830. }
  5831. }
  5832. }
  5833. return min, nil
  5834. case "MAX":
  5835. var max interface{}
  5836. for _, row := range rows {
  5837. if len(fn.Args) > 0 {
  5838. val, _ := e.evalExpr(fn.Args[0], row)
  5839. if val != nil && (max == nil || compare(val, max) > 0) {
  5840. max = val
  5841. }
  5842. }
  5843. }
  5844. return max, nil
  5845. case "TOTAL":
  5846. var sum float64
  5847. for _, row := range rows {
  5848. if len(fn.Args) > 0 {
  5849. val, _ := e.evalExpr(fn.Args[0], row)
  5850. if val != nil {
  5851. sum += toFloat(val)
  5852. }
  5853. }
  5854. }
  5855. return sum, nil
  5856. case "STRING_AGG":
  5857. if len(fn.Args) == 0 {
  5858. return nil, fmt.Errorf("STRING_AGG requires at least one argument")
  5859. }
  5860. separator := ""
  5861. if len(fn.Args) > 1 && len(rows) > 0 {
  5862. sep, err := e.evalExpr(fn.Args[1], rows[0])
  5863. if err != nil {
  5864. return nil, err
  5865. }
  5866. if sep == nil {
  5867. return nil, nil
  5868. }
  5869. separator = toString(sep)
  5870. }
  5871. var seen map[string]struct{}
  5872. if fn.Distinct {
  5873. seen = make(map[string]struct{})
  5874. }
  5875. var parts []string
  5876. for _, row := range rows {
  5877. val, err := e.evalExpr(fn.Args[0], row)
  5878. if err != nil {
  5879. return nil, err
  5880. }
  5881. if val == nil {
  5882. continue
  5883. }
  5884. text := toString(val)
  5885. if fn.Distinct {
  5886. if _, exists := seen[text]; exists {
  5887. continue
  5888. }
  5889. seen[text] = struct{}{}
  5890. }
  5891. parts = append(parts, text)
  5892. }
  5893. if len(parts) == 0 {
  5894. return nil, nil
  5895. }
  5896. return strings.Join(parts, separator), nil
  5897. case "GROUP_CONCAT":
  5898. if len(fn.Args) == 0 {
  5899. return nil, fmt.Errorf("GROUP_CONCAT requires at least one argument")
  5900. }
  5901. var seen map[string]struct{}
  5902. if fn.Distinct {
  5903. seen = make(map[string]struct{})
  5904. }
  5905. var builder strings.Builder
  5906. count := 0
  5907. for _, row := range rows {
  5908. val, err := e.evalExpr(fn.Args[0], row)
  5909. if err != nil {
  5910. return nil, err
  5911. }
  5912. if val == nil {
  5913. continue
  5914. }
  5915. text := toString(val)
  5916. if fn.Distinct {
  5917. if _, exists := seen[text]; exists {
  5918. continue
  5919. }
  5920. seen[text] = struct{}{}
  5921. }
  5922. if count > 0 {
  5923. separator := ","
  5924. if len(fn.Args) > 1 {
  5925. sep, err := e.evalExpr(fn.Args[1], row)
  5926. if err != nil {
  5927. return nil, err
  5928. }
  5929. separator = toString(sep)
  5930. }
  5931. builder.WriteString(separator)
  5932. }
  5933. builder.WriteString(text)
  5934. count++
  5935. }
  5936. if count == 0 {
  5937. return nil, nil
  5938. }
  5939. return builder.String(), nil
  5940. case "JSON_GROUP_ARRAY", "JSONB_GROUP_ARRAY":
  5941. arr := make([]interface{}, 0, len(rows))
  5942. var seen map[string]struct{}
  5943. if fn.Distinct {
  5944. seen = make(map[string]struct{})
  5945. }
  5946. for _, row := range rows {
  5947. var val interface{}
  5948. if len(fn.Args) > 0 {
  5949. val, _ = e.evalExpr(fn.Args[0], row)
  5950. }
  5951. if fn.Distinct {
  5952. key := fmt.Sprintf("%v", val)
  5953. if _, exists := seen[key]; exists {
  5954. continue
  5955. }
  5956. seen[key] = struct{}{}
  5957. }
  5958. arr = append(arr, jsonArgToNode(val))
  5959. }
  5960. s, err := jsonEncode(arr)
  5961. if err != nil {
  5962. return nil, err
  5963. }
  5964. return jsonText(s), nil
  5965. default:
  5966. if isAggregateCallName(name) {
  5967. return nil, fmt.Errorf("unsupported aggregate function: %s", name)
  5968. }
  5969. // Non-aggregate scalar function: evaluate args through aggregate context
  5970. // (so COUNT/MIN/etc. inside NULLIF/COALESCE work correctly).
  5971. return e.evalExprWithAggregates(expr, rows)
  5972. }
  5973. }
  5974. // isAggregateCallName lists the aggregate functions handled by
  5975. // evalAggregateExpr. Keeping dispatch and evaluation on the same list prevents
  5976. // an unhandled aggregate from recursing between the aggregate and expression
  5977. // evaluators.
  5978. func isAggregateCallName(name string) bool {
  5979. switch strings.ToUpper(name) {
  5980. case "COUNT", "SUM", "AVG", "MIN", "MAX", "TOTAL", "GROUP_CONCAT", "STRING_AGG",
  5981. "JSON_GROUP_ARRAY", "JSONB_GROUP_ARRAY":
  5982. return true
  5983. default:
  5984. return false
  5985. }
  5986. }
  5987. // evalExprWithAggregates evaluates an expression that may contain aggregate functions
  5988. func (e *Executor) evalExprWithAggregates(expr parser.Expr, rows []storage.Row) (interface{}, error) {
  5989. switch ex := expr.(type) {
  5990. case *parser.BinaryExpr:
  5991. left, err := e.evalExprWithAggregates(ex.Left, rows)
  5992. if err != nil {
  5993. return nil, err
  5994. }
  5995. right, err := e.evalExprWithAggregates(ex.Right, rows)
  5996. if err != nil {
  5997. return nil, err
  5998. }
  5999. // Use the same logic as evalBinaryExpr to preserve integer semantics.
  6000. combined := &parser.BinaryExpr{Op: ex.Op}
  6001. return e.applyBinaryOp(combined.Op, left, right)
  6002. case *parser.FunctionCall:
  6003. name := strings.ToUpper(ex.Name)
  6004. if isAggregateCallName(name) {
  6005. return e.evalAggregateExpr(expr, rows)
  6006. }
  6007. // Non-aggregate: evaluate each arg with aggregate context, then apply scalar.
  6008. args := make([]interface{}, len(ex.Args))
  6009. for i, arg := range ex.Args {
  6010. v, err := e.evalExprWithAggregates(arg, rows)
  6011. if err != nil {
  6012. return nil, err
  6013. }
  6014. args[i] = v
  6015. }
  6016. return e.evalBuiltinFunction(name, args)
  6017. case *parser.ParenExpr:
  6018. return e.evalExprWithAggregates(ex.Expr, rows)
  6019. case *parser.UnaryExpr:
  6020. operand, err := e.evalExprWithAggregates(ex.Operand, rows)
  6021. if err != nil {
  6022. return nil, err
  6023. }
  6024. switch ex.Op {
  6025. case lexer.TokenPlus:
  6026. return operand, nil
  6027. case lexer.TokenMinus:
  6028. if operand == nil {
  6029. return nil, nil
  6030. }
  6031. if isIntVal(operand) {
  6032. return -toInt64(operand), nil
  6033. }
  6034. return -toFloat(operand), nil
  6035. case lexer.TokenNOT:
  6036. if operand == nil {
  6037. return nil, nil // NOT NULL = NULL
  6038. }
  6039. return !toBool(operand), nil
  6040. default:
  6041. return nil, fmt.Errorf("unsupported unary operator: %v", ex.Op)
  6042. }
  6043. case *parser.CastExpr:
  6044. // Evaluate inner expression with aggregate context, then apply cast.
  6045. val, err := e.evalExprWithAggregates(ex.Expr, rows)
  6046. if err != nil {
  6047. return nil, err
  6048. }
  6049. if val == nil {
  6050. return nil, nil
  6051. }
  6052. switch strings.ToUpper(ex.Type.Name) {
  6053. case "INTEGER", "INT", "BIGINT", "SMALLINT", "TINYINT", "SIGNED":
  6054. if isIntVal(val) {
  6055. return toInt64(val), nil
  6056. }
  6057. return int64(toFloat(val)), nil
  6058. case "REAL", "FLOAT", "DOUBLE", "NUMERIC", "DECIMAL":
  6059. return toFloat(val), nil
  6060. case "TEXT", "VARCHAR", "CHAR", "STRING":
  6061. return fmt.Sprintf("%v", val), nil
  6062. }
  6063. return val, nil
  6064. case *parser.CaseExpr:
  6065. var operand interface{}
  6066. if ex.Operand != nil {
  6067. operand, _ = e.evalExprWithAggregates(ex.Operand, rows)
  6068. }
  6069. for _, when := range ex.Whens {
  6070. condVal, _ := e.evalExprWithAggregates(when.Condition, rows)
  6071. var matched bool
  6072. if ex.Operand != nil {
  6073. matched = operand != nil && condVal != nil && compare(operand, condVal) == 0
  6074. } else {
  6075. matched = toBool(condVal)
  6076. }
  6077. if matched {
  6078. return e.evalExprWithAggregates(when.Result, rows)
  6079. }
  6080. }
  6081. if ex.Else != nil {
  6082. return e.evalExprWithAggregates(ex.Else, rows)
  6083. }
  6084. return nil, nil
  6085. case *parser.IsNullExpr:
  6086. val, err := e.evalExprWithAggregates(ex.Left, rows)
  6087. if err != nil {
  6088. return nil, err
  6089. }
  6090. isNull := val == nil
  6091. if ex.Not {
  6092. return !isNull, nil
  6093. }
  6094. return isNull, nil
  6095. case *parser.IsDistinctExpr:
  6096. left, err := e.evalExprWithAggregates(ex.Left, rows)
  6097. if err != nil {
  6098. return nil, err
  6099. }
  6100. right, err := e.evalExprWithAggregates(ex.Right, rows)
  6101. if err != nil {
  6102. return nil, err
  6103. }
  6104. distinct := false
  6105. switch {
  6106. case left == nil && right == nil:
  6107. distinct = false
  6108. case left == nil || right == nil:
  6109. distinct = true
  6110. default:
  6111. distinct = compare(left, right) != 0
  6112. }
  6113. if ex.Not {
  6114. return !distinct, nil
  6115. }
  6116. return distinct, nil
  6117. case *parser.BetweenExpr:
  6118. val, err := e.evalExprWithAggregates(ex.Left, rows)
  6119. if err != nil {
  6120. return nil, err
  6121. }
  6122. low, err := e.evalExprWithAggregates(ex.Low, rows)
  6123. if err != nil {
  6124. return nil, err
  6125. }
  6126. high, err := e.evalExprWithAggregates(ex.High, rows)
  6127. if err != nil {
  6128. return nil, err
  6129. }
  6130. if ex.Not {
  6131. // NOT BETWEEN: val < low OR val > high
  6132. var lessThan, greaterThan interface{}
  6133. if val == nil || low == nil {
  6134. lessThan = nil
  6135. } else {
  6136. lessThan = compare(val, low) < 0
  6137. }
  6138. if val == nil || high == nil {
  6139. greaterThan = nil
  6140. } else {
  6141. greaterThan = compare(val, high) > 0
  6142. }
  6143. // Three-valued OR
  6144. if toBool(lessThan) || toBool(greaterThan) {
  6145. return true, nil
  6146. }
  6147. if lessThan == nil || greaterThan == nil {
  6148. return nil, nil
  6149. }
  6150. return false, nil
  6151. } else {
  6152. // BETWEEN: val >= low AND val <= high
  6153. if val == nil {
  6154. return nil, nil
  6155. }
  6156. if low == nil {
  6157. if high != nil && compare(val, high) > 0 {
  6158. return false, nil
  6159. }
  6160. return nil, nil
  6161. }
  6162. if compare(val, low) < 0 {
  6163. return false, nil
  6164. }
  6165. if high == nil {
  6166. return nil, nil
  6167. }
  6168. return compare(val, high) <= 0, nil
  6169. }
  6170. case *parser.InExpr:
  6171. left, err := e.evalExprWithAggregates(ex.Left, rows)
  6172. if err != nil {
  6173. return nil, err
  6174. }
  6175. // Handle subquery
  6176. if ex.Subquery != nil {
  6177. var result *Result
  6178. var err error
  6179. if e.subqueryCache != nil && e.outerRow == nil {
  6180. if cached, ok := e.subqueryCache[ex.Subquery]; ok {
  6181. result = cached
  6182. } else {
  6183. result, err = e.executeSelect(ex.Subquery)
  6184. if err == nil {
  6185. e.subqueryCache[ex.Subquery] = result
  6186. }
  6187. }
  6188. } else {
  6189. result, err = e.executeSelect(ex.Subquery)
  6190. }
  6191. if err != nil {
  6192. return nil, fmt.Errorf("IN subquery error: %w", err)
  6193. }
  6194. if len(result.Columns) != 1 {
  6195. return nil, fmt.Errorf("subquery in IN must return exactly one column")
  6196. }
  6197. if left == nil {
  6198. return nil, nil
  6199. }
  6200. sawNull := false
  6201. for _, resultRow := range result.Rows {
  6202. if len(resultRow) == 0 {
  6203. continue
  6204. }
  6205. v := resultRow[0]
  6206. if v == nil {
  6207. sawNull = true
  6208. continue
  6209. }
  6210. if compare(left, v) == 0 {
  6211. if ex.Not {
  6212. return false, nil
  6213. }
  6214. return true, nil
  6215. }
  6216. }
  6217. if sawNull {
  6218. return nil, nil
  6219. }
  6220. if ex.Not {
  6221. return true, nil
  6222. }
  6223. return false, nil
  6224. }
  6225. // Handle value list
  6226. if len(ex.Values) == 0 {
  6227. return ex.Not, nil
  6228. }
  6229. if left == nil {
  6230. return nil, nil
  6231. }
  6232. sawNull := false
  6233. for _, val := range ex.Values {
  6234. v, err := e.evalExprWithAggregates(val, rows)
  6235. if err != nil {
  6236. return nil, err
  6237. }
  6238. if v == nil {
  6239. sawNull = true
  6240. continue
  6241. }
  6242. if compare(left, v) == 0 {
  6243. if ex.Not {
  6244. return false, nil
  6245. }
  6246. return true, nil
  6247. }
  6248. }
  6249. if sawNull {
  6250. return nil, nil
  6251. }
  6252. if ex.Not {
  6253. return true, nil
  6254. }
  6255. return false, nil
  6256. default:
  6257. // Literals and non-aggregate expressions.
  6258. if len(rows) > 0 {
  6259. return e.evalExpr(expr, rows[0])
  6260. }
  6261. return e.evalExpr(expr, storage.Row{})
  6262. }
  6263. }
  6264. // Helper functions
  6265. func (e *Executor) getSelectColumns(stmt *parser.SelectStmt, schema *storage.Schema) []string {
  6266. var columns []string
  6267. for _, col := range stmt.Columns {
  6268. if col.Star {
  6269. for _, c := range schema.Columns {
  6270. columns = append(columns, c.Name)
  6271. }
  6272. } else if col.Alias != "" {
  6273. columns = append(columns, col.Alias)
  6274. } else if ref, ok := col.Expr.(*parser.ColumnRef); ok {
  6275. columns = append(columns, ref.Column)
  6276. } else {
  6277. columns = append(columns, fmt.Sprintf("column%d", len(columns)+1))
  6278. }
  6279. }
  6280. return columns
  6281. }
  6282. func (e *Executor) hasAggregates(columns []parser.SelectColumn) bool {
  6283. for _, col := range columns {
  6284. if e.isAggregate(col.Expr) {
  6285. return true
  6286. }
  6287. }
  6288. return false
  6289. }
  6290. func (e *Executor) isAggregate(expr parser.Expr) bool {
  6291. if _, ok := expr.(*parser.WindowExpr); ok {
  6292. // Window functions are computed after grouping; they are not aggregates.
  6293. return false
  6294. }
  6295. if fn, ok := expr.(*parser.FunctionCall); ok {
  6296. name := strings.ToUpper(fn.Name)
  6297. if isAggregateCallName(name) {
  6298. return true
  6299. }
  6300. // Non-aggregate function: check if any arg contains an aggregate.
  6301. for _, arg := range fn.Args {
  6302. if e.isAggregate(arg) {
  6303. return true
  6304. }
  6305. }
  6306. return false
  6307. }
  6308. switch ex := expr.(type) {
  6309. case *parser.UnaryExpr:
  6310. return e.isAggregate(ex.Operand)
  6311. case *parser.BinaryExpr:
  6312. return e.isAggregate(ex.Left) || e.isAggregate(ex.Right)
  6313. case *parser.ParenExpr:
  6314. return e.isAggregate(ex.Expr)
  6315. case *parser.CaseExpr:
  6316. if ex.Operand != nil && e.isAggregate(ex.Operand) {
  6317. return true
  6318. }
  6319. for _, w := range ex.Whens {
  6320. if e.isAggregate(w.Condition) || e.isAggregate(w.Result) {
  6321. return true
  6322. }
  6323. }
  6324. if ex.Else != nil {
  6325. return e.isAggregate(ex.Else)
  6326. }
  6327. case *parser.CastExpr:
  6328. return e.isAggregate(ex.Expr)
  6329. case *parser.IsNullExpr:
  6330. return e.isAggregate(ex.Left)
  6331. case *parser.IsDistinctExpr:
  6332. return e.isAggregate(ex.Left) || e.isAggregate(ex.Right)
  6333. case *parser.BetweenExpr:
  6334. return e.isAggregate(ex.Left) || e.isAggregate(ex.Low) || e.isAggregate(ex.High)
  6335. case *parser.InExpr:
  6336. if e.isAggregate(ex.Left) {
  6337. return true
  6338. }
  6339. for _, val := range ex.Values {
  6340. if e.isAggregate(val) {
  6341. return true
  6342. }
  6343. }
  6344. return false
  6345. }
  6346. return false
  6347. }
  6348. // resolveGroupByAliases replaces GROUP BY references that name a SELECT alias
  6349. // with the aliased expression. SQLite allows `GROUP BY alias`, so grouping must
  6350. // use the same expression the projection evaluates.
  6351. func (e *Executor) resolveGroupByAliases(groupBy []parser.Expr, selectCols []parser.SelectColumn) []parser.Expr {
  6352. if len(groupBy) == 0 {
  6353. return groupBy
  6354. }
  6355. aliases := make(map[string]parser.Expr, len(selectCols))
  6356. for _, col := range selectCols {
  6357. if col.Alias != "" && col.Expr != nil {
  6358. aliases[strings.ToUpper(col.Alias)] = col.Expr
  6359. }
  6360. }
  6361. if len(aliases) == 0 {
  6362. return groupBy
  6363. }
  6364. out := make([]parser.Expr, len(groupBy))
  6365. for i, expr := range groupBy {
  6366. if ref, ok := expr.(*parser.ColumnRef); ok {
  6367. if target, ok := aliases[strings.ToUpper(ref.Column)]; ok {
  6368. out[i] = target
  6369. continue
  6370. }
  6371. }
  6372. out[i] = expr
  6373. }
  6374. return out
  6375. }
  6376. func (e *Executor) buildGroupKey(groupBy []parser.Expr, row storage.Row) string {
  6377. var parts []string
  6378. for _, expr := range groupBy {
  6379. val, _ := e.evalExpr(expr, row)
  6380. parts = append(parts, fmt.Sprintf("%v", val))
  6381. }
  6382. return strings.Join(parts, "|")
  6383. }
  6384. // resolveOrderByPositions replaces positional ORDER BY expressions (e.g. ORDER BY 1)
  6385. // with the corresponding SELECT column expressions per SQL-92 semantics.
  6386. func resolveOrderByPositions(orderBy []parser.OrderByItem, selectCols []parser.SelectColumn) []parser.OrderByItem {
  6387. result := make([]parser.OrderByItem, len(orderBy))
  6388. for i, item := range orderBy {
  6389. if lit, ok := item.Expr.(*parser.LiteralExpr); ok {
  6390. if pos, err := strconv.Atoi(lit.Value); err == nil && pos >= 1 && pos <= len(selectCols) {
  6391. col := selectCols[pos-1]
  6392. if col.Expr != nil {
  6393. result[i] = parser.OrderByItem{Expr: col.Expr, Desc: item.Desc, NullsOrder: item.NullsOrder}
  6394. continue
  6395. }
  6396. }
  6397. }
  6398. result[i] = item
  6399. }
  6400. return result
  6401. }
  6402. // orderByLess reports whether key slice a sorts before b under orderBy.
  6403. // Keys are precomputed per-row ORDER BY expression values, one per item.
  6404. func orderByLess(a, b []interface{}, orderBy []parser.OrderByItem) bool {
  6405. for i, item := range orderBy {
  6406. av, bv := a[i], b[i]
  6407. if av == nil || bv == nil {
  6408. if av == nil && bv == nil {
  6409. continue
  6410. }
  6411. // SQLite treats NULL as smaller than any value, so the default puts
  6412. // NULLs first for ASC and last for DESC. NULLS FIRST/LAST overrides it.
  6413. nullsFirst := !item.Desc
  6414. switch item.NullsOrder {
  6415. case parser.NullsFirst:
  6416. nullsFirst = true
  6417. case parser.NullsLast:
  6418. nullsFirst = false
  6419. }
  6420. if av == nil {
  6421. return nullsFirst
  6422. }
  6423. return !nullsFirst
  6424. }
  6425. cmp := compare(av, bv)
  6426. if cmp != 0 {
  6427. if item.Desc {
  6428. return cmp > 0
  6429. }
  6430. return cmp < 0
  6431. }
  6432. }
  6433. return false
  6434. }
  6435. // sortKeyOrder returns a permutation of [0..len(keys)) that sorts the keys
  6436. // ascending per orderBy.
  6437. func sortKeyOrder(keys [][]interface{}, orderBy []parser.OrderByItem) []int {
  6438. order := make([]int, len(keys))
  6439. for i := range order {
  6440. order[i] = i
  6441. }
  6442. sort.Slice(order, func(a, b int) bool {
  6443. return orderByLess(keys[order[a]], keys[order[b]], orderBy)
  6444. })
  6445. return order
  6446. }
  6447. // topNHeap is a bounded max-heap that keeps the k smallest elements (per
  6448. // orderByLess) seen so far.
  6449. type topNHeap struct {
  6450. keys [][]interface{}
  6451. idx []int
  6452. orderBy []parser.OrderByItem
  6453. }
  6454. func (h *topNHeap) Len() int { return len(h.idx) }
  6455. func (h *topNHeap) Less(i, j int) bool {
  6456. return orderByLess(h.keys[h.idx[j]], h.keys[h.idx[i]], h.orderBy)
  6457. }
  6458. func (h *topNHeap) Swap(i, j int) { h.idx[i], h.idx[j] = h.idx[j], h.idx[i] }
  6459. func (h *topNHeap) Push(x interface{}) { h.idx = append(h.idx, x.(int)) }
  6460. func (h *topNHeap) Pop() interface{} {
  6461. n := len(h.idx)
  6462. x := h.idx[n-1]
  6463. h.idx = h.idx[:n-1]
  6464. return x
  6465. }
  6466. // topNKeyOrder returns the indices of the k smallest keys (per orderByLess) in
  6467. // ascending order, without fully sorting all n elements. If k >= n it falls
  6468. // back to a full sort.
  6469. func topNKeyOrder(keys [][]interface{}, orderBy []parser.OrderByItem, k int) []int {
  6470. if k <= 0 {
  6471. return nil
  6472. }
  6473. if k >= len(keys) {
  6474. return sortKeyOrder(keys, orderBy)
  6475. }
  6476. h := &topNHeap{keys: keys, orderBy: orderBy, idx: make([]int, 0, k)}
  6477. for i := range keys {
  6478. if h.Len() < k {
  6479. heap.Push(h, i)
  6480. } else if orderByLess(keys[i], keys[h.idx[0]], orderBy) {
  6481. h.idx[0] = i
  6482. heap.Fix(h, 0)
  6483. }
  6484. }
  6485. selected := append([]int(nil), h.idx...)
  6486. sort.Slice(selected, func(a, b int) bool {
  6487. return orderByLess(keys[selected[a]], keys[selected[b]], orderBy)
  6488. })
  6489. return selected
  6490. }
  6491. func reorderRows(rows []storage.Row, order []int) {
  6492. tmp := make([]storage.Row, len(rows))
  6493. for i, idx := range order {
  6494. tmp[i] = rows[idx]
  6495. }
  6496. copy(rows, tmp)
  6497. }
  6498. // sortRowKeys precomputes the ORDER BY expression value for each row so each
  6499. // expression is evaluated once per row instead of O(n log n) times.
  6500. func (e *Executor) sortRowKeys(rows []storage.Row, orderBy []parser.OrderByItem) [][]interface{} {
  6501. keys := make([][]interface{}, len(rows))
  6502. for i, row := range rows {
  6503. ks := make([]interface{}, len(orderBy))
  6504. for j, item := range orderBy {
  6505. ks[j], _ = e.evalExpr(item.Expr, row)
  6506. }
  6507. keys[i] = ks
  6508. }
  6509. return keys
  6510. }
  6511. func (e *Executor) sortRows(rows []storage.Row, orderBy []parser.OrderByItem) {
  6512. order := sortKeyOrder(e.sortRowKeys(rows, orderBy), orderBy)
  6513. reorderRows(rows, order)
  6514. }
  6515. // topNRows sorts only enough to keep the k smallest rows (per orderBy).
  6516. func (e *Executor) topNRows(rows []storage.Row, orderBy []parser.OrderByItem, k int) []storage.Row {
  6517. order := topNKeyOrder(e.sortRowKeys(rows, orderBy), orderBy, k)
  6518. out := make([]storage.Row, len(order))
  6519. for i, idx := range order {
  6520. out[i] = rows[idx]
  6521. }
  6522. return out
  6523. }
  6524. // orderAndLimitRows applies ORDER BY (with a bounded top-N selection when a
  6525. // LIMIT is present), then OFFSET and LIMIT, preserving SQL semantics.
  6526. func (e *Executor) orderAndLimitRows(rows []storage.Row, orderBy []parser.OrderByItem, limitExpr, offsetExpr parser.Expr, selectCols []parser.SelectColumn) []storage.Row {
  6527. orderBy = resolveOrderByPositions(orderBy, selectCols)
  6528. var offset, limit int
  6529. hasOffset := offsetExpr != nil
  6530. hasLimit := limitExpr != nil
  6531. if hasOffset {
  6532. offset = e.evalIntExpr(offsetExpr)
  6533. }
  6534. if hasLimit {
  6535. limit = e.evalIntExpr(limitExpr)
  6536. }
  6537. if len(orderBy) > 0 {
  6538. if hasLimit && limit >= 0 {
  6539. k := offset + limit
  6540. if k >= 0 && k < len(rows) {
  6541. rows = e.topNRows(rows, orderBy, k)
  6542. } else {
  6543. e.sortRows(rows, orderBy)
  6544. }
  6545. } else {
  6546. e.sortRows(rows, orderBy)
  6547. }
  6548. }
  6549. if hasOffset {
  6550. if offset < len(rows) {
  6551. rows = rows[offset:]
  6552. } else {
  6553. rows = nil
  6554. }
  6555. }
  6556. if hasLimit {
  6557. if limit < len(rows) {
  6558. rows = rows[:limit]
  6559. }
  6560. }
  6561. return rows
  6562. }
  6563. // resultRowKey evaluates a single ORDER BY item against a result row, honoring
  6564. // select-column aliases exactly like the previous sortResultRows implementation.
  6565. func (e *Executor) resultRowKey(result *Result, rowIdx int, item parser.OrderByItem, columnNames []string) interface{} {
  6566. if ref, ok := item.Expr.(*parser.ColumnRef); ok && ref.Table == "" {
  6567. for idx, name := range columnNames {
  6568. if strings.EqualFold(name, ref.Column) {
  6569. if idx < len(result.Rows[rowIdx]) {
  6570. return result.Rows[rowIdx][idx]
  6571. }
  6572. }
  6573. }
  6574. }
  6575. row := e.resultRowToStorageRow(result, rowIdx)
  6576. v, _ := e.evalExpr(item.Expr, row)
  6577. return v
  6578. }
  6579. // resultRowKeys precomputes the ORDER BY expression value for each result row.
  6580. func (e *Executor) resultRowKeys(result *Result, orderBy []parser.OrderByItem, columnNames []string) [][]interface{} {
  6581. keys := make([][]interface{}, len(result.Rows))
  6582. for i := range result.Rows {
  6583. ks := make([]interface{}, len(orderBy))
  6584. for j, item := range orderBy {
  6585. ks[j] = e.resultRowKey(result, i, item, columnNames)
  6586. }
  6587. keys[i] = ks
  6588. }
  6589. return keys
  6590. }
  6591. // sortResultRows sorts Result.Rows based on ORDER BY clauses.
  6592. // It handles column aliases by matching them against the select columns.
  6593. func (e *Executor) sortResultRows(result *Result, orderBy []parser.OrderByItem, selectColumns []parser.SelectColumn, columnNames []string) {
  6594. orderBy = resolveOrderByPositions(orderBy, selectColumns)
  6595. order := sortKeyOrder(e.resultRowKeys(result, orderBy, columnNames), orderBy)
  6596. rows := make([][]interface{}, len(order))
  6597. for i, idx := range order {
  6598. rows[i] = result.Rows[idx]
  6599. }
  6600. result.Rows = rows
  6601. }
  6602. // orderAndLimitResultRows applies ORDER BY (with bounded top-N selection when a
  6603. // LIMIT is present), then OFFSET and LIMIT, to a Result's rows.
  6604. func (e *Executor) orderAndLimitResultRows(result *Result, orderBy []parser.OrderByItem, limitExpr, offsetExpr parser.Expr, selectCols []parser.SelectColumn, columnNames []string) {
  6605. orderBy = resolveOrderByPositions(orderBy, selectCols)
  6606. var offset, limit int
  6607. hasOffset := offsetExpr != nil
  6608. hasLimit := limitExpr != nil
  6609. if hasOffset {
  6610. offset = e.evalIntExpr(offsetExpr)
  6611. }
  6612. if hasLimit {
  6613. limit = e.evalIntExpr(limitExpr)
  6614. }
  6615. if len(orderBy) > 0 {
  6616. if hasLimit && limit >= 0 {
  6617. k := offset + limit
  6618. if k >= 0 && k < len(result.Rows) {
  6619. order := topNKeyOrder(e.resultRowKeys(result, orderBy, columnNames), orderBy, k)
  6620. rows := make([][]interface{}, len(order))
  6621. for i, idx := range order {
  6622. rows[i] = result.Rows[idx]
  6623. }
  6624. result.Rows = rows
  6625. } else {
  6626. e.sortResultRows(result, orderBy, nil, columnNames)
  6627. }
  6628. } else {
  6629. e.sortResultRows(result, orderBy, nil, columnNames)
  6630. }
  6631. }
  6632. if hasOffset {
  6633. if offset < len(result.Rows) {
  6634. result.Rows = result.Rows[offset:]
  6635. } else {
  6636. result.Rows = nil
  6637. }
  6638. result.RowCount = len(result.Rows)
  6639. }
  6640. if hasLimit {
  6641. if limit < len(result.Rows) {
  6642. result.Rows = result.Rows[:limit]
  6643. }
  6644. result.RowCount = len(result.Rows)
  6645. }
  6646. }
  6647. // resultRowToStorageRow converts a Result row back to storage.Row for expression evaluation.
  6648. func (e *Executor) resultRowToStorageRow(result *Result, rowIdx int) storage.Row {
  6649. row := make(storage.Row)
  6650. for colIdx, colName := range result.Columns {
  6651. if colIdx < len(result.Rows[rowIdx]) {
  6652. row[colName] = result.Rows[rowIdx][colIdx]
  6653. }
  6654. }
  6655. return row
  6656. }
  6657. func (e *Executor) evalIntExpr(expr parser.Expr) int {
  6658. val, _ := e.evalExpr(expr, nil)
  6659. return int(toFloat(val))
  6660. }
  6661. // Type conversion helpers
  6662. func isIntVal(v interface{}) bool {
  6663. switch v.(type) {
  6664. case int64, int, bool:
  6665. return true
  6666. default:
  6667. return false
  6668. }
  6669. }
  6670. func toInt64(v interface{}) int64 {
  6671. switch val := v.(type) {
  6672. case int64:
  6673. return val
  6674. case int:
  6675. return int64(val)
  6676. case float64:
  6677. return int64(val)
  6678. case bool:
  6679. if val {
  6680. return 1
  6681. }
  6682. return 0
  6683. default:
  6684. return 0
  6685. }
  6686. }
  6687. func toFloat(v interface{}) float64 {
  6688. switch val := v.(type) {
  6689. case nil:
  6690. return 0
  6691. case int64:
  6692. return float64(val)
  6693. case int:
  6694. return float64(val)
  6695. case float64:
  6696. return val
  6697. case bool:
  6698. if val {
  6699. return 1
  6700. }
  6701. return 0
  6702. case string:
  6703. f, _ := strconv.ParseFloat(val, 64)
  6704. return f
  6705. default:
  6706. return 0
  6707. }
  6708. }
  6709. func toBool(v interface{}) bool {
  6710. switch val := v.(type) {
  6711. case nil:
  6712. return false
  6713. case bool:
  6714. return val
  6715. case int64:
  6716. return val != 0
  6717. case int:
  6718. return val != 0
  6719. case float64:
  6720. return val != 0
  6721. case string:
  6722. return val != "" && val != "0" && strings.ToLower(val) != "false"
  6723. default:
  6724. return false
  6725. }
  6726. }
  6727. func toString(v interface{}) string {
  6728. if v == nil {
  6729. return ""
  6730. }
  6731. switch t := v.(type) {
  6732. case string:
  6733. return t
  6734. case []byte:
  6735. return string(t)
  6736. case jsonText:
  6737. return string(t)
  6738. case bool:
  6739. if t {
  6740. return "1"
  6741. }
  6742. return "0"
  6743. case int:
  6744. return strconv.FormatInt(int64(t), 10)
  6745. case int64:
  6746. return strconv.FormatInt(t, 10)
  6747. case uint:
  6748. return strconv.FormatUint(uint64(t), 10)
  6749. case uint64:
  6750. return strconv.FormatUint(t, 10)
  6751. case float32:
  6752. return formatSQLiteReal(float64(t))
  6753. case float64:
  6754. return formatSQLiteReal(t)
  6755. default:
  6756. return fmt.Sprintf("%v", v)
  6757. }
  6758. }
  6759. func compare(a, b interface{}) int {
  6760. if a == nil && b == nil {
  6761. return 0
  6762. }
  6763. if a == nil {
  6764. return -1
  6765. }
  6766. if b == nil {
  6767. return 1
  6768. }
  6769. // Try numeric comparison
  6770. fa, oka := toNumeric(a)
  6771. fb, okb := toNumeric(b)
  6772. if oka && okb {
  6773. if fa < fb {
  6774. return -1
  6775. }
  6776. if fa > fb {
  6777. return 1
  6778. }
  6779. return 0
  6780. }
  6781. // String comparison
  6782. sa := toString(a)
  6783. sb := toString(b)
  6784. return strings.Compare(sa, sb)
  6785. }
  6786. func toNumeric(v interface{}) (float64, bool) {
  6787. switch val := v.(type) {
  6788. case int64:
  6789. return float64(val), true
  6790. case int:
  6791. return float64(val), true
  6792. case float64:
  6793. return val, true
  6794. case string:
  6795. f, err := strconv.ParseFloat(val, 64)
  6796. return f, err == nil
  6797. default:
  6798. return 0, false
  6799. }
  6800. }
  6801. // splitANDClauses flattens a tree of AND binary expressions into a slice of leaf conditions.
  6802. func splitANDClauses(expr parser.Expr) []parser.Expr {
  6803. if bin, ok := expr.(*parser.BinaryExpr); ok && bin.Op == lexer.TokenAND {
  6804. left := splitANDClauses(bin.Left)
  6805. right := splitANDClauses(bin.Right)
  6806. return append(left, right...)
  6807. }
  6808. return []parser.Expr{expr}
  6809. }
  6810. // collectColumnRefs returns all unqualified column names referenced in an expression.
  6811. func collectColumnRefs(expr parser.Expr) []string {
  6812. var refs []string
  6813. var hasSubquery bool
  6814. var walk func(parser.Expr)
  6815. walk = func(e parser.Expr) {
  6816. if e == nil {
  6817. return
  6818. }
  6819. switch n := e.(type) {
  6820. case *parser.ColumnRef:
  6821. refs = append(refs, n.Column)
  6822. case *parser.BinaryExpr:
  6823. walk(n.Left)
  6824. walk(n.Right)
  6825. case *parser.UnaryExpr:
  6826. walk(n.Operand)
  6827. case *parser.InExpr:
  6828. walk(n.Left)
  6829. // Check for subquery
  6830. if n.Subquery != nil {
  6831. hasSubquery = true
  6832. }
  6833. for _, v := range n.Values {
  6834. walk(v)
  6835. }
  6836. case *parser.BetweenExpr:
  6837. walk(n.Left)
  6838. walk(n.Low)
  6839. walk(n.High)
  6840. case *parser.LikeExpr:
  6841. walk(n.Left)
  6842. walk(n.Pattern)
  6843. case *parser.IsNullExpr:
  6844. walk(n.Left)
  6845. case *parser.IsDistinctExpr:
  6846. walk(n.Left)
  6847. walk(n.Right)
  6848. case *parser.CaseExpr:
  6849. walk(n.Operand)
  6850. for _, w := range n.Whens {
  6851. walk(w.Condition)
  6852. walk(w.Result)
  6853. }
  6854. walk(n.Else)
  6855. case *parser.FunctionCall:
  6856. for _, a := range n.Args {
  6857. walk(a)
  6858. }
  6859. case *parser.ParenExpr:
  6860. walk(n.Expr)
  6861. case *parser.CastExpr:
  6862. walk(n.Expr)
  6863. case *parser.SubqueryExpr:
  6864. // Subqueries may reference outer columns
  6865. hasSubquery = true
  6866. case *parser.ExistsExpr:
  6867. // EXISTS subqueries may reference outer columns
  6868. hasSubquery = true
  6869. case *parser.LiteralExpr:
  6870. // Literals have no column refs
  6871. }
  6872. }
  6873. walk(expr)
  6874. // If we have subqueries, add a sentinel value to indicate non-constant
  6875. if hasSubquery {
  6876. refs = append(refs, "__subquery__")
  6877. }
  6878. return refs
  6879. }
  6880. type tableColRef struct{ tbl, col string }
  6881. // collectTableColumnRefs returns all column references with their table qualifier (may be "").
  6882. func collectTableColumnRefs(expr parser.Expr) []tableColRef {
  6883. var refs []tableColRef
  6884. var walk func(parser.Expr)
  6885. walk = func(e parser.Expr) {
  6886. if e == nil {
  6887. return
  6888. }
  6889. switch n := e.(type) {
  6890. case *parser.ColumnRef:
  6891. refs = append(refs, tableColRef{tbl: n.Table, col: n.Column})
  6892. case *parser.BinaryExpr:
  6893. walk(n.Left)
  6894. walk(n.Right)
  6895. case *parser.UnaryExpr:
  6896. walk(n.Operand)
  6897. case *parser.InExpr:
  6898. walk(n.Left)
  6899. for _, v := range n.Values {
  6900. walk(v)
  6901. }
  6902. case *parser.BetweenExpr:
  6903. walk(n.Left)
  6904. walk(n.Low)
  6905. walk(n.High)
  6906. case *parser.LikeExpr:
  6907. walk(n.Left)
  6908. walk(n.Pattern)
  6909. case *parser.IsNullExpr:
  6910. walk(n.Left)
  6911. case *parser.IsDistinctExpr:
  6912. walk(n.Left)
  6913. walk(n.Right)
  6914. case *parser.CaseExpr:
  6915. walk(n.Operand)
  6916. for _, w := range n.Whens {
  6917. walk(w.Condition)
  6918. walk(w.Result)
  6919. }
  6920. walk(n.Else)
  6921. case *parser.FunctionCall:
  6922. for _, a := range n.Args {
  6923. walk(a)
  6924. }
  6925. }
  6926. }
  6927. walk(expr)
  6928. return refs
  6929. }
  6930. // combineAND combines a list of expressions with AND.
  6931. func combineAND(clauses []parser.Expr) parser.Expr {
  6932. if len(clauses) == 0 {
  6933. return nil
  6934. }
  6935. result := clauses[0]
  6936. for _, c := range clauses[1:] {
  6937. result = &parser.BinaryExpr{Left: result, Op: lexer.TokenAND, Right: c}
  6938. }
  6939. return result
  6940. }
  6941. // matchLike matches a string against a SQL LIKE pattern.
  6942. func matchLike(s, pattern string) bool {
  6943. // Simple implementation - convert to lowercase for case-insensitive matching
  6944. s = strings.ToLower(s)
  6945. pattern = strings.ToLower(pattern)
  6946. return matchLikeHelper(s, pattern)
  6947. }
  6948. func matchLikeHelper(s, p string) bool {
  6949. if p == "" {
  6950. return s == ""
  6951. }
  6952. if p[0] == '%' {
  6953. // % matches any sequence
  6954. for i := 0; i <= len(s); i++ {
  6955. if matchLikeHelper(s[i:], p[1:]) {
  6956. return true
  6957. }
  6958. }
  6959. return false
  6960. }
  6961. if s == "" {
  6962. return false
  6963. }
  6964. if p[0] == '_' || p[0] == s[0] {
  6965. return matchLikeHelper(s[1:], p[1:])
  6966. }
  6967. return false
  6968. }
  6969. // matchGlob matches a string against a GLOB pattern.
  6970. // GLOB uses * for any sequence and ? for single character (case-sensitive).
  6971. func matchGlob(pattern, s string) bool {
  6972. return matchGlobHelper(pattern, s)
  6973. }
  6974. func matchGlobHelper(p, s string) bool {
  6975. if p == "" {
  6976. return s == ""
  6977. }
  6978. if p[0] == '*' {
  6979. // * matches any sequence
  6980. for i := 0; i <= len(s); i++ {
  6981. if matchGlobHelper(p[1:], s[i:]) {
  6982. return true
  6983. }
  6984. }
  6985. return false
  6986. }
  6987. if s == "" {
  6988. return false
  6989. }
  6990. if p[0] == '?' || p[0] == s[0] {
  6991. return matchGlobHelper(p[1:], s[1:])
  6992. }
  6993. // Handle character classes [...]
  6994. if p[0] == '[' {
  6995. end := strings.Index(p, "]")
  6996. if end > 0 {
  6997. class := p[1:end]
  6998. match := false
  6999. negate := false
  7000. if len(class) > 0 && class[0] == '^' {
  7001. negate = true
  7002. class = class[1:]
  7003. }
  7004. for _, c := range class {
  7005. if byte(c) == s[0] {
  7006. match = true
  7007. break
  7008. }
  7009. }
  7010. if negate {
  7011. match = !match
  7012. }
  7013. if match {
  7014. return matchGlobHelper(p[end+1:], s[1:])
  7015. }
  7016. }
  7017. }
  7018. return false
  7019. }
  7020. // applyDistinct removes duplicate rows from the result
  7021. func (e *Executor) applyDistinct(rows [][]interface{}) [][]interface{} {
  7022. if len(rows) == 0 {
  7023. return rows
  7024. }
  7025. seen := make(map[string]bool)
  7026. uniqueRows := make([][]interface{}, 0)
  7027. for _, row := range rows {
  7028. // Create a key from all column values
  7029. key := ""
  7030. for i, val := range row {
  7031. if i > 0 {
  7032. key += "\x00" // Use null byte as separator
  7033. }
  7034. key += fmt.Sprintf("%v", val)
  7035. }
  7036. if !seen[key] {
  7037. seen[key] = true
  7038. uniqueRows = append(uniqueRows, row)
  7039. }
  7040. }
  7041. return uniqueRows
  7042. }