executor.go 211 KB

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