2
0

executor.go 204 KB

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