executor.go 211 KB

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