2
0

executor.go 227 KB

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