executor.go 237 KB

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