executor.go 205 KB

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