executor.go 234 KB

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