executor.go 152 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959
  1. package executor
  2. import (
  3. "container/heap"
  4. "errors"
  5. "fmt"
  6. "math/rand"
  7. "sort"
  8. "strconv"
  9. "strings"
  10. "github.com/danfragoso/pizzasql-next/pkg/analyzer"
  11. "github.com/danfragoso/pizzasql-next/pkg/lexer"
  12. "github.com/danfragoso/pizzasql-next/pkg/parser"
  13. "github.com/danfragoso/pizzasql-next/pkg/storage"
  14. "github.com/danfragoso/pizzasql-next/pkg/version"
  15. )
  16. // Executor executes SQL statements.
  17. type Executor struct {
  18. schema *storage.SchemaManager
  19. table *storage.TableManager
  20. session *storage.Session
  21. analyzer *analyzer.Analyzer
  22. catalog *analyzer.Catalog
  23. // Last SchemaManager version reflected in catalog.
  24. catalogVersion uint64
  25. // Multi-database support
  26. attachedDatabases map[string]*DatabaseConnection // alias -> connection
  27. currentDatabase string // current database alias (default is "main")
  28. // Transaction state
  29. inTransaction bool
  30. savepoints []string // stack of savepoint names
  31. savepointPositions []int // session mutation-log positions for each savepoint
  32. // Subquery context for correlated subqueries
  33. outerRow storage.Row
  34. // Per-query cache for non-correlated IN (SELECT ...) subquery results.
  35. // Keyed by subquery AST pointer; valid for one top-level Execute call.
  36. subqueryCache map[*parser.SelectStmt]*Result
  37. // Per-query cache for decorrelated scalar aggregate subqueries.
  38. // Keyed by subquery AST pointer; valid for one top-level Execute call.
  39. correlatedAggCache map[*parser.SelectStmt]*correlatedAggCache
  40. // In-memory view registry: view name (lowercase) → SELECT AST.
  41. views map[string]*parser.SelectStmt
  42. // Session-local SQLite compatibility state, tracked per connection so
  43. // last_insert_rowid()/changes()/total_changes() reflect this session only.
  44. lastInsertRowID int64 // rowid of the most recent successful INSERT
  45. changes int64 // rows changed by the most recent INSERT/UPDATE/DELETE
  46. totalChanges int64 // rows changed since this connection opened (monotonic)
  47. }
  48. type correlatedAggCache struct {
  49. values map[string]interface{}
  50. defaultValue interface{}
  51. }
  52. type correlatedAggSpec struct {
  53. innerKey parser.Expr
  54. outerKey *parser.ColumnRef
  55. aggExpr parser.Expr
  56. }
  57. // DatabaseConnection represents an attached database.
  58. type DatabaseConnection struct {
  59. Alias string
  60. Path string // Database path or identifier
  61. Schema *storage.SchemaManager
  62. Table *storage.TableManager
  63. }
  64. // New creates a new executor.
  65. func New(schema *storage.SchemaManager, table *storage.TableManager) *Executor {
  66. catalog := analyzer.NewCatalog()
  67. executor := &Executor{
  68. schema: schema,
  69. table: table,
  70. session: storage.NewSession(schema, table),
  71. analyzer: analyzer.New(catalog),
  72. catalog: catalog,
  73. attachedDatabases: make(map[string]*DatabaseConnection),
  74. currentDatabase: "main",
  75. views: make(map[string]*parser.SelectStmt),
  76. }
  77. // Register the main database
  78. executor.attachedDatabases["main"] = &DatabaseConnection{
  79. Alias: "main",
  80. Path: schema.GetDatabaseName(),
  81. Schema: schema,
  82. Table: table,
  83. }
  84. return executor
  85. }
  86. // NewSessionExecutor returns a new executor sharing the same schema and table
  87. // managers but with fresh per-executor state (transaction, subquery caches,
  88. // views). It is used to isolate concurrent requests that must not share mutable
  89. // executor state.
  90. func (e *Executor) NewSessionExecutor() *Executor {
  91. exec := New(e.schema, e.table)
  92. exec.SyncCatalog()
  93. return exec
  94. }
  95. // SyncCatalog synchronizes the analyzer catalog with the storage schema.
  96. func (e *Executor) SyncCatalog() error {
  97. tables, err := e.schema.ListTables()
  98. if err != nil {
  99. return err
  100. }
  101. storageTables := make(map[string]struct{}, len(tables))
  102. for _, tableName := range tables {
  103. storageTables[strings.ToUpper(tableName)] = struct{}{}
  104. schema, err := e.schema.GetSchema(tableName)
  105. if err != nil {
  106. continue
  107. }
  108. // Drop table from catalog if it exists, then recreate with updated schema
  109. e.catalog.DropTable(tableName)
  110. e.catalog.CreateTable(schema.ToAnalyzerTableInfo())
  111. }
  112. for _, table := range e.catalog.GetTables() {
  113. if table.IsView {
  114. continue
  115. }
  116. if _, exists := storageTables[strings.ToUpper(table.Name)]; !exists {
  117. e.catalog.DropTable(table.Name)
  118. }
  119. }
  120. e.catalogVersion = e.schema.Version()
  121. return nil
  122. }
  123. // Execute executes a SQL statement.
  124. func (e *Executor) Execute(stmt parser.Statement) (*Result, error) {
  125. if _, beginning := stmt.(*parser.BeginStmt); !beginning && !e.inTransaction {
  126. e.schema.LockStatement()
  127. defer e.schema.UnlockStatement()
  128. }
  129. e.subqueryCache = make(map[*parser.SelectStmt]*Result)
  130. e.correlatedAggCache = make(map[*parser.SelectStmt]*correlatedAggCache)
  131. defer func() {
  132. e.subqueryCache = nil
  133. e.correlatedAggCache = nil
  134. }()
  135. // PRAGMA doesn't need analysis. SQLite catalog-introspection pragmas
  136. // (index_list, index_info, table_xinfo) are answered by the catalog agent
  137. // first; everything else falls through to the built-in handler.
  138. if pragma, ok := stmt.(*parser.PragmaStmt); ok {
  139. if res, handled, err := e.sqliteCatalogPragma(pragma); handled {
  140. return res, err
  141. }
  142. return e.executePragma(pragma)
  143. }
  144. // EXPLAIN doesn't need analysis
  145. if explain, ok := stmt.(*parser.ExplainStmt); ok {
  146. return e.executeExplain(explain)
  147. }
  148. // Transaction statements don't need analysis
  149. switch s := stmt.(type) {
  150. case *parser.BeginStmt:
  151. return e.executeBegin(s)
  152. case *parser.CommitStmt:
  153. return e.executeCommit(s)
  154. case *parser.RollbackStmt:
  155. return e.executeRollback(s)
  156. case *parser.SavepointStmt:
  157. return e.executeSavepoint(s)
  158. case *parser.ReleaseStmt:
  159. return e.executeRelease(s)
  160. case *parser.CreateIndexStmt:
  161. return e.executeCreateIndex(s)
  162. case *parser.DropIndexStmt:
  163. return e.executeDropIndex(s)
  164. case *parser.CreateViewStmt:
  165. return e.executeCreateView(s)
  166. case *parser.DropViewStmt:
  167. return e.executeDropView(s)
  168. case *parser.AttachStmt:
  169. return e.executeAttach(s)
  170. case *parser.DetachStmt:
  171. return e.executeDetach(s)
  172. }
  173. // SQLite catalog/metadata dispatch. SELECTs against sqlite_master /
  174. // sqlite_schema must be answered before the analyzer, which would otherwise
  175. // reject those virtual tables as unknown. Falls through when unhandled.
  176. if sel, ok := stmt.(*parser.SelectStmt); ok {
  177. if res, handled, err := e.sqliteCatalogSelect(sel); handled {
  178. return res, err
  179. }
  180. }
  181. // Analyze first. If the cached analyzer catalog is stale because schema was
  182. // changed through another executor/API path, resync from storage and retry
  183. // once before returning table/column-not-found errors.
  184. if err := e.analyzeWithCatalogRetry(stmt); err != nil {
  185. return nil, err
  186. }
  187. switch s := stmt.(type) {
  188. case *parser.SelectStmt:
  189. return e.executeSelect(s)
  190. case *parser.InsertStmt:
  191. return e.executeInsert(s)
  192. case *parser.UpdateStmt:
  193. return e.executeUpdate(s)
  194. case *parser.DeleteStmt:
  195. return e.executeDelete(s)
  196. case *parser.CreateTableStmt:
  197. return e.executeCreateTable(s)
  198. case *parser.DropTableStmt:
  199. return e.executeDropTable(s)
  200. case *parser.CreateIndexStmt:
  201. return e.executeCreateIndex(s)
  202. case *parser.DropIndexStmt:
  203. return e.executeDropIndex(s)
  204. case *parser.AlterTableStmt:
  205. return e.executeAlterTable(s)
  206. default:
  207. return nil, fmt.Errorf("unsupported statement type: %T", stmt)
  208. }
  209. }
  210. func (e *Executor) analyzeWithCatalogRetry(stmt parser.Statement) error {
  211. if e.catalogVersion != e.schema.Version() {
  212. if err := e.SyncCatalog(); err != nil {
  213. return err
  214. }
  215. }
  216. a := analyzer.New(e.catalog)
  217. err := a.Analyze(stmt)
  218. if err == nil {
  219. return nil
  220. }
  221. if !isCatalogMiss(err) {
  222. return err
  223. }
  224. if syncErr := e.SyncCatalog(); syncErr != nil {
  225. return err
  226. }
  227. a = analyzer.New(e.catalog)
  228. return a.Analyze(stmt)
  229. }
  230. func isCatalogMiss(err error) bool {
  231. var analysisErr *analyzer.AnalysisError
  232. if !errors.As(err, &analysisErr) {
  233. return false
  234. }
  235. return analysisErr.Type == analyzer.ErrTableNotFound ||
  236. analysisErr.Type == analyzer.ErrColumnNotFound
  237. }
  238. // isCountStarSingleTable reports whether the statement is the safe COUNT(*)
  239. // shape eligible for the metadata fast path: a single-table SELECT with exactly
  240. // one COUNT(*) column and no filters, grouping, DISTINCT, JOIN, subquery, or
  241. // LIMIT/OFFSET. Anything else returns false so unsupported shapes use the
  242. // normal scan path.
  243. func isCountStarSingleTable(stmt *parser.SelectStmt) bool {
  244. if stmt.Compound != nil || stmt.Distinct {
  245. return false
  246. }
  247. if stmt.Where != nil || stmt.Having != nil {
  248. return false
  249. }
  250. if len(stmt.GroupBy) > 0 || len(stmt.OrderBy) > 0 {
  251. return false
  252. }
  253. if stmt.Limit != nil || stmt.Offset != nil {
  254. return false
  255. }
  256. if len(stmt.From) != 1 {
  257. return false
  258. }
  259. ref := stmt.From[0]
  260. if ref.Subquery != nil || ref.Join != nil {
  261. return false
  262. }
  263. if len(stmt.Columns) != 1 || stmt.Columns[0].Star {
  264. return false
  265. }
  266. fn, ok := stmt.Columns[0].Expr.(*parser.FunctionCall)
  267. if !ok {
  268. return false
  269. }
  270. if !strings.EqualFold(fn.Name, "count") || !fn.Star || len(fn.Args) > 0 {
  271. return false
  272. }
  273. return true
  274. }
  275. // executeSelect executes a SELECT statement (or compound SELECT).
  276. func (e *Executor) executeSelect(stmt *parser.SelectStmt) (*Result, error) {
  277. if stmt.Compound != nil {
  278. return e.executeCompound(stmt.Compound)
  279. }
  280. if len(stmt.From) == 0 {
  281. // SELECT without FROM (e.g., SELECT 1+1)
  282. return e.executeSelectExpr(stmt)
  283. }
  284. // Check if FROM clause is a subquery (derived table)
  285. if stmt.From[0].Subquery != nil {
  286. return e.executeSelectFromSubquery(stmt)
  287. }
  288. tableName := stmt.From[0].Name
  289. // Transparently expand view references as derived-table subqueries.
  290. if viewDef, ok := e.views[strings.ToLower(tableName)]; ok {
  291. alias := stmt.From[0].Alias
  292. if alias == "" {
  293. alias = tableName
  294. }
  295. modifiedStmt := *stmt
  296. modifiedFrom := make([]parser.TableRef, len(stmt.From))
  297. copy(modifiedFrom, stmt.From)
  298. modifiedFrom[0] = parser.TableRef{Subquery: viewDef, Alias: alias}
  299. modifiedStmt.From = modifiedFrom
  300. return e.executeSelectFromSubquery(&modifiedStmt)
  301. }
  302. schema, err := e.schema.GetSchema(tableName)
  303. if err != nil {
  304. return nil, err
  305. }
  306. // COUNT(*) fast path: exact metadata-based count for the safe single-table
  307. // shape with no filters/grouping/distinct/join. Any unsupported shape falls
  308. // through to the normal scan path.
  309. if isCountStarSingleTable(stmt) {
  310. count, err := e.session.CountFast(tableName)
  311. if err != nil {
  312. return nil, err
  313. }
  314. result := NewResult("SELECT")
  315. if stmt.Columns[0].Alias != "" {
  316. result.AddColumn(stmt.Columns[0].Alias)
  317. } else {
  318. result.AddColumn("column1")
  319. }
  320. result.AddRow(int64(count))
  321. return result, nil
  322. }
  323. // Multi-table FROM (comma-separated implicit cross join): collect and cross join all tables,
  324. // then apply WHERE after. Don't push WHERE down here — conditions reference multiple tables.
  325. isMultiTable := len(stmt.From) > 1 && stmt.From[0].Join == nil
  326. // Optimize constant WHERE clauses
  327. var constantWhereResult *bool
  328. if stmt.Where != nil && !isMultiTable {
  329. // Check if WHERE clause is a constant expression (doesn't reference any columns)
  330. refs := collectColumnRefs(stmt.Where)
  331. if len(refs) == 0 {
  332. // Evaluate the constant expression
  333. val, err := e.evalExpr(stmt.Where, nil)
  334. if err == nil {
  335. result := toBool(val)
  336. constantWhereResult = &result
  337. }
  338. }
  339. }
  340. // If WHERE is constant false, check if we have aggregates first
  341. if constantWhereResult != nil && !*constantWhereResult {
  342. // If query has GROUP BY, return empty result (no groups match)
  343. // If query has aggregates but no GROUP BY, evaluate them on empty row set
  344. if e.hasAggregates(stmt.Columns) {
  345. if len(stmt.GroupBy) > 0 {
  346. // GROUP BY with no matching rows: return empty result (no groups)
  347. // Fall through to the non-aggregate case below
  348. } else {
  349. // Aggregate without GROUP BY: return single row with aggregate results on empty set
  350. return e.executeAggregateSelect(stmt, []storage.Row{}, schema)
  351. }
  352. }
  353. // Non-aggregate query with WHERE false: return empty result
  354. result := NewResult("SELECT")
  355. for i, col := range stmt.Columns {
  356. if col.Alias != "" {
  357. result.AddColumn(col.Alias)
  358. } else if ref, ok := col.Expr.(*parser.ColumnRef); ok {
  359. result.AddColumn(ref.Column)
  360. } else if col.Star {
  361. for _, c := range schema.Columns {
  362. result.AddColumn(c.Name)
  363. }
  364. } else {
  365. result.AddColumn(fmt.Sprintf("column%d", i+1))
  366. }
  367. }
  368. return result, nil
  369. }
  370. // Try to use index for WHERE clause (single-table only)
  371. var rows []storage.Row
  372. usedIndex := false
  373. // If WHERE is constant true, skip it during table scan
  374. effectiveWhere := stmt.Where
  375. if constantWhereResult != nil && *constantWhereResult {
  376. effectiveWhere = nil
  377. }
  378. if effectiveWhere != nil && !isMultiTable {
  379. // Check if we can use an index
  380. colName, colValue, isEquality := e.extractIndexableCondition(stmt.Where)
  381. if isEquality {
  382. if strings.EqualFold(schema.PrimaryKey, colName) {
  383. row, getErr := e.session.GetByPK(tableName, fmt.Sprintf("%v", colValue))
  384. if getErr == nil {
  385. normalizeRowBySchema(row, schema)
  386. rows = []storage.Row{row}
  387. usedIndex = true
  388. } else if getErr == storage.ErrKeyNotFound {
  389. rows = []storage.Row{}
  390. usedIndex = true
  391. } else {
  392. return nil, getErr
  393. }
  394. } else {
  395. // Look for an index on this column
  396. indexes, _ := e.schema.ListTableIndexes(tableName)
  397. for _, idx := range indexes {
  398. if len(idx.Columns) == 1 && strings.EqualFold(idx.Columns[0].Name, colName) {
  399. rows, err = e.session.SelectByIndex(tableName, idx.Name, colValue)
  400. if err == nil {
  401. usedIndex = true
  402. for i := range rows {
  403. normalizeRowBySchema(rows[i], schema)
  404. }
  405. }
  406. break
  407. }
  408. }
  409. }
  410. }
  411. }
  412. // Fall back to full table scan if no index used
  413. if !usedIndex {
  414. var filterErr error
  415. var filter func(storage.Row) bool
  416. if effectiveWhere != nil && stmt.From[0].Alias == "" && !isMultiTable && stmt.From[0].Join == nil {
  417. filter = func(row storage.Row) bool {
  418. val, ferr := e.evalExpr(effectiveWhere, row)
  419. if ferr != nil {
  420. filterErr = ferr
  421. return false
  422. }
  423. return toBool(val)
  424. }
  425. }
  426. rows, err = e.session.Select(tableName, filter)
  427. if filterErr != nil {
  428. return nil, filterErr
  429. }
  430. for _, row := range rows {
  431. normalizeRowBySchema(row, schema)
  432. }
  433. }
  434. if err != nil {
  435. return nil, err
  436. }
  437. // Add table alias to rows if there's an explicit alias
  438. if stmt.From[0].Alias != "" {
  439. for i := range rows {
  440. rows[i] = e.addTableAlias(rows[i], stmt.From[0].Alias)
  441. }
  442. } else if isMultiTable {
  443. // For multi-table cross joins without alias, prefix columns with table name
  444. // so WHERE can distinguish t3.a3 from t7.a7.
  445. for i := range rows {
  446. rows[i] = e.addTableAlias(rows[i], tableName)
  447. }
  448. }
  449. // Apply WHERE for single-table with alias (after alias mapping so alias.col refs work).
  450. // A query with a JOIN defers WHERE until after the join, because the WHERE may
  451. // reference columns from the joined table.
  452. if effectiveWhere != nil && stmt.From[0].Alias != "" && !isMultiTable && stmt.From[0].Join == nil {
  453. var filterErr error
  454. var filtered []storage.Row
  455. for _, row := range rows {
  456. val, ferr := e.evalExpr(effectiveWhere, row)
  457. if ferr != nil {
  458. filterErr = ferr
  459. break
  460. }
  461. if toBool(val) {
  462. filtered = append(filtered, row)
  463. }
  464. }
  465. if filterErr != nil {
  466. return nil, filterErr
  467. }
  468. rows = filtered
  469. }
  470. // Handle explicit JOINs from the first FROM entry (single-table+JOIN path)
  471. if !isMultiTable && len(stmt.From) > 0 && stmt.From[0].Join != nil {
  472. rows, err = e.executeJoins(stmt.From[0], rows)
  473. if err != nil {
  474. return nil, err
  475. }
  476. // Cross-join with any remaining comma-separated FROM entries (mixed JOIN+comma syntax)
  477. for _, tref := range stmt.From[1:] {
  478. rightRows, rerr := e.session.Select(tref.Name, nil)
  479. if rerr != nil {
  480. return nil, rerr
  481. }
  482. rightAlias := tref.Alias
  483. if rightAlias == "" {
  484. rightAlias = tref.Name
  485. }
  486. for i := range rightRows {
  487. rightRows[i] = e.addTableAlias(rightRows[i], rightAlias)
  488. }
  489. var joined []storage.Row
  490. for _, l := range rows {
  491. for _, r := range rightRows {
  492. m := make(storage.Row, len(l)+len(r))
  493. for k, v := range l {
  494. m[k] = v
  495. }
  496. for k, v := range r {
  497. m[k] = v
  498. }
  499. joined = append(joined, m)
  500. }
  501. }
  502. rows = joined
  503. // Handle JOINs within this tref too
  504. if tref.Join != nil {
  505. rows, err = e.executeJoins(tref, rows)
  506. if err != nil {
  507. return nil, err
  508. }
  509. }
  510. }
  511. // Apply WHERE after all joins. It is intentionally deferred past the base
  512. // scan for JOIN queries because the WHERE may reference joined-table columns.
  513. if effectiveWhere != nil {
  514. var filtered []storage.Row
  515. for _, row := range rows {
  516. val, _ := e.evalExpr(effectiveWhere, row)
  517. if toBool(val) {
  518. filtered = append(filtered, row)
  519. }
  520. }
  521. rows = filtered
  522. }
  523. }
  524. // Handle implicit cross joins (comma-separated FROM tables)
  525. if isMultiTable {
  526. // Build the column-set for each table so we can push WHERE conditions down.
  527. type tableInfo struct {
  528. alias string
  529. name string
  530. colsSet map[string]bool // lower-case column names for this table
  531. }
  532. allTableInfos := make([]tableInfo, len(stmt.From))
  533. for i, tref := range stmt.From {
  534. alias := tref.Alias
  535. if alias == "" {
  536. alias = tref.Name
  537. }
  538. sch, _ := e.schema.GetSchema(tref.Name)
  539. cols := map[string]bool{}
  540. if sch != nil {
  541. for _, c := range sch.Columns {
  542. cols[strings.ToLower(c.Name)] = true
  543. }
  544. }
  545. allTableInfos[i] = tableInfo{alias: alias, name: tref.Name, colsSet: cols}
  546. }
  547. // Split WHERE into AND-clauses and determine which tables each clause touches.
  548. var andClauses []parser.Expr
  549. if stmt.Where != nil {
  550. andClauses = splitANDClauses(stmt.Where)
  551. }
  552. // For each table, collect conditions that reference only its own columns.
  553. tableFilters := make([][]parser.Expr, len(stmt.From))
  554. var crossFilters []parser.Expr
  555. for _, clause := range andClauses {
  556. refs := collectColumnRefs(clause)
  557. ownerIdx := -1
  558. cross := false
  559. for _, ref := range refs {
  560. colLower := strings.ToLower(ref)
  561. found := -1
  562. for i, ti := range allTableInfos {
  563. if ti.colsSet[colLower] {
  564. if found == -1 {
  565. found = i
  566. } else if found != i {
  567. cross = true
  568. break
  569. }
  570. }
  571. }
  572. if cross {
  573. break
  574. }
  575. if found != -1 {
  576. if ownerIdx == -1 {
  577. ownerIdx = found
  578. } else if ownerIdx != found {
  579. cross = true
  580. break
  581. }
  582. }
  583. }
  584. if cross || ownerIdx == -1 {
  585. crossFilters = append(crossFilters, clause)
  586. } else {
  587. tableFilters[ownerIdx] = append(tableFilters[ownerIdx], clause)
  588. }
  589. }
  590. // Build cross-condition adjacency: for each cross filter, record which table indices it touches.
  591. type crossEdge struct{ a, b int }
  592. var crossEdges []crossEdge
  593. for _, clause := range crossFilters {
  594. refs := collectColumnRefs(clause)
  595. touched := map[int]bool{}
  596. for _, ref := range refs {
  597. cl := strings.ToLower(ref)
  598. for j, ti := range allTableInfos {
  599. if ti.colsSet[cl] {
  600. touched[j] = true
  601. }
  602. }
  603. }
  604. idxs := make([]int, 0, len(touched))
  605. for j := range touched {
  606. idxs = append(idxs, j)
  607. }
  608. if len(idxs) == 2 {
  609. crossEdges = append(crossEdges, crossEdge{idxs[0], idxs[1]})
  610. }
  611. }
  612. // Build alias-to-index map for applyWhenSeen.
  613. aliasToIdx := make(map[string]int, len(allTableInfos))
  614. for i, ti := range allTableInfos {
  615. aliasToIdx[strings.ToLower(ti.alias)] = i
  616. }
  617. // Helper: find cross-conditions applicable when seenSet is fully present.
  618. // A condition is applicable only when ALL tables it references are in seenSet.
  619. // For table-qualified refs (e.g. cor0.col2), we check the qualifying alias is seen.
  620. applyWhenSeen := func(seenSet map[int]bool, pending []parser.Expr) (applicable, still []parser.Expr) {
  621. for _, clause := range pending {
  622. tableRefs := collectTableColumnRefs(clause)
  623. ok := true
  624. for _, tr := range tableRefs {
  625. col := strings.ToLower(tr.col)
  626. tbl := strings.ToLower(tr.tbl)
  627. found := false
  628. if tbl != "" {
  629. // Explicit table qualifier — check that qualifying alias is seen.
  630. if idx, exists := aliasToIdx[tbl]; exists && seenSet[idx] {
  631. found = true
  632. }
  633. } else {
  634. // Unqualified — any seen table with this column satisfies it.
  635. for j, tti := range allTableInfos {
  636. if tti.colsSet[col] && seenSet[j] {
  637. found = true
  638. break
  639. }
  640. }
  641. }
  642. if !found {
  643. ok = false
  644. break
  645. }
  646. }
  647. if ok {
  648. applicable = append(applicable, clause)
  649. } else {
  650. still = append(still, clause)
  651. }
  652. }
  653. return
  654. }
  655. // Helper: inline cross-join two row-sets, applying a predicate.
  656. inlineJoin := func(left, right []storage.Row, pred parser.Expr) []storage.Row {
  657. out := make([]storage.Row, 0, len(left))
  658. for _, l := range left {
  659. for _, r := range right {
  660. m := make(storage.Row, len(l)+len(r))
  661. for k, v := range l {
  662. m[k] = v
  663. }
  664. for k, v := range r {
  665. m[k] = v
  666. }
  667. if pred != nil {
  668. val, _ := e.evalExpr(pred, m)
  669. if !toBool(val) {
  670. continue
  671. }
  672. }
  673. out = append(out, m)
  674. }
  675. }
  676. return out
  677. }
  678. // Pre-join connected components of "cross-only" tables (0 single-table filters,
  679. // connected via cross conditions to other cross-only tables).
  680. // This prevents n^k explosions when bare tables are joined last.
  681. crossOnlySet := map[int]bool{}
  682. for i := range stmt.From {
  683. if len(tableFilters[i]) > 0 {
  684. continue
  685. }
  686. for _, ce := range crossEdges {
  687. if ce.a == i || ce.b == i {
  688. crossOnlySet[i] = true
  689. break
  690. }
  691. }
  692. }
  693. // BFS: find connected components among cross-only tables.
  694. compOf := make([]int, len(stmt.From))
  695. for i := range compOf {
  696. compOf[i] = -1
  697. }
  698. nComps := 0
  699. for start := range stmt.From {
  700. if !crossOnlySet[start] || compOf[start] != -1 {
  701. continue
  702. }
  703. queue := []int{start}
  704. compOf[start] = nComps
  705. for len(queue) > 0 {
  706. cur := queue[0]
  707. queue = queue[1:]
  708. for _, ce := range crossEdges {
  709. var nb int = -1
  710. if ce.a == cur && crossOnlySet[ce.b] {
  711. nb = ce.b
  712. } else if ce.b == cur && crossOnlySet[ce.a] {
  713. nb = ce.a
  714. }
  715. if nb >= 0 && compOf[nb] == -1 {
  716. compOf[nb] = nComps
  717. queue = append(queue, nb)
  718. }
  719. }
  720. }
  721. nComps++
  722. }
  723. // Group cross-only tables by component.
  724. compTbls := make([][]int, nComps)
  725. for i, c := range compOf {
  726. if c >= 0 {
  727. compTbls[c] = append(compTbls[c], i)
  728. }
  729. }
  730. // Pre-join each component with ≥2 tables; collect results as virtual units.
  731. type virtualUnit struct {
  732. tableIdxs map[int]bool
  733. rows []storage.Row
  734. }
  735. var virtuals []virtualUnit
  736. preJoined := map[int]bool{} // original table indices consumed into virtuals
  737. remaining := make([]parser.Expr, len(crossFilters))
  738. copy(remaining, crossFilters)
  739. for _, comp := range compTbls {
  740. if len(comp) < 2 {
  741. continue
  742. }
  743. // Pick seed: table with most cross-edges within component.
  744. seed := comp[0]
  745. for _, idx := range comp[1:] {
  746. degIdx, degSeed := 0, 0
  747. for _, ce := range crossEdges {
  748. if ce.a == idx || ce.b == idx {
  749. degIdx++
  750. }
  751. if ce.a == seed || ce.b == seed {
  752. degSeed++
  753. }
  754. }
  755. if degIdx > degSeed {
  756. seed = idx
  757. }
  758. }
  759. // Load seed.
  760. seedRows, rerr := e.session.Select(stmt.From[seed].Name, nil)
  761. if rerr != nil {
  762. return nil, rerr
  763. }
  764. seedSchema, _ := e.schema.GetSchema(stmt.From[seed].Name)
  765. for j := range seedRows {
  766. normalizeRowBySchema(seedRows[j], seedSchema)
  767. seedRows[j] = e.addTableAlias(seedRows[j], allTableInfos[seed].alias)
  768. }
  769. vSeen := map[int]bool{seed: true}
  770. // Greedy within-component join.
  771. compSet := map[int]bool{}
  772. for _, idx := range comp {
  773. compSet[idx] = true
  774. }
  775. for len(vSeen) < len(comp) {
  776. // Pick next table in component with cross-edge to vSeen.
  777. nextC := -1
  778. for _, idx := range comp {
  779. if vSeen[idx] {
  780. continue
  781. }
  782. for _, ce := range crossEdges {
  783. if (ce.a == idx && vSeen[ce.b]) || (ce.b == idx && vSeen[ce.a]) {
  784. nextC = idx
  785. break
  786. }
  787. }
  788. if nextC >= 0 {
  789. break
  790. }
  791. }
  792. if nextC < 0 {
  793. for _, idx := range comp {
  794. if !vSeen[idx] {
  795. nextC = idx
  796. break
  797. }
  798. }
  799. }
  800. nextRows, rerr := e.session.Select(stmt.From[nextC].Name, nil)
  801. if rerr != nil {
  802. return nil, rerr
  803. }
  804. nextSchema, _ := e.schema.GetSchema(stmt.From[nextC].Name)
  805. for j := range nextRows {
  806. normalizeRowBySchema(nextRows[j], nextSchema)
  807. nextRows[j] = e.addTableAlias(nextRows[j], allTableInfos[nextC].alias)
  808. }
  809. vSeen[nextC] = true
  810. appl, still := applyWhenSeen(vSeen, remaining)
  811. remaining = still
  812. var pred parser.Expr
  813. if len(appl) > 0 {
  814. pred = combineAND(appl)
  815. }
  816. seedRows = inlineJoin(seedRows, nextRows, pred)
  817. }
  818. virtuals = append(virtuals, virtualUnit{tableIdxs: vSeen, rows: seedRows})
  819. for idx := range vSeen {
  820. preJoined[idx] = true
  821. }
  822. }
  823. // Build greedy order for non-pre-joined tables.
  824. // Score: single-table filter count + 1000 × cross-edges to already-joined.
  825. orderNonPJ := make([]int, 0, len(stmt.From)-len(preJoined))
  826. inOrderNPJ := make([]bool, len(stmt.From))
  827. best := -1
  828. for j := range stmt.From {
  829. if preJoined[j] {
  830. continue
  831. }
  832. if best < 0 || len(tableFilters[j]) > len(tableFilters[best]) {
  833. best = j
  834. }
  835. }
  836. if best >= 0 {
  837. orderNonPJ = append(orderNonPJ, best)
  838. inOrderNPJ[best] = true
  839. }
  840. for len(orderNonPJ)+len(preJoined) < len(stmt.From) {
  841. joined := map[int]bool{}
  842. for _, idx := range orderNonPJ {
  843. joined[idx] = true
  844. }
  845. nextIdx := -1
  846. nextScore := -1
  847. for j := range stmt.From {
  848. if inOrderNPJ[j] || preJoined[j] {
  849. continue
  850. }
  851. score := len(tableFilters[j])
  852. for _, ce := range crossEdges {
  853. if (ce.a == j && joined[ce.b]) || (ce.b == j && joined[ce.a]) {
  854. score += 1000
  855. }
  856. }
  857. if score > nextScore {
  858. nextScore = score
  859. nextIdx = j
  860. }
  861. }
  862. if nextIdx < 0 {
  863. for j := range stmt.From {
  864. if !inOrderNPJ[j] && !preJoined[j] {
  865. nextIdx = j
  866. break
  867. }
  868. }
  869. }
  870. if nextIdx >= 0 {
  871. orderNonPJ = append(orderNonPJ, nextIdx)
  872. inOrderNPJ[nextIdx] = true
  873. }
  874. }
  875. // Load the initial rows for the first non-pre-joined table (or use the already-loaded rows).
  876. seenTables := map[int]bool{}
  877. if len(orderNonPJ) > 0 {
  878. first := orderNonPJ[0]
  879. if first != 0 {
  880. rows, err = e.session.Select(stmt.From[first].Name, nil)
  881. if err != nil {
  882. return nil, err
  883. }
  884. firstSchema, _ := e.schema.GetSchema(stmt.From[first].Name)
  885. for i := range rows {
  886. normalizeRowBySchema(rows[i], firstSchema)
  887. rows[i] = e.addTableAlias(rows[i], allTableInfos[first].alias)
  888. }
  889. }
  890. if len(tableFilters[first]) > 0 {
  891. pred := combineAND(tableFilters[first])
  892. var filtered []storage.Row
  893. for _, row := range rows {
  894. val, _ := e.evalExpr(pred, row)
  895. if toBool(val) {
  896. filtered = append(filtered, row)
  897. }
  898. }
  899. rows = filtered
  900. }
  901. seenTables[first] = true
  902. // Join remaining non-pre-joined tables.
  903. for _, idx := range orderNonPJ[1:] {
  904. ti := allTableInfos[idx]
  905. rightRows, rerr := e.session.Select(stmt.From[idx].Name, nil)
  906. if rerr != nil {
  907. return nil, rerr
  908. }
  909. rightSchema, _ := e.schema.GetSchema(stmt.From[idx].Name)
  910. for j := range rightRows {
  911. normalizeRowBySchema(rightRows[j], rightSchema)
  912. rightRows[j] = e.addTableAlias(rightRows[j], ti.alias)
  913. }
  914. if len(tableFilters[idx]) > 0 {
  915. pred := combineAND(tableFilters[idx])
  916. var filtered []storage.Row
  917. for _, row := range rightRows {
  918. val, _ := e.evalExpr(pred, row)
  919. if toBool(val) {
  920. filtered = append(filtered, row)
  921. }
  922. }
  923. rightRows = filtered
  924. }
  925. seenTables[idx] = true
  926. appl, still := applyWhenSeen(seenTables, remaining)
  927. remaining = still
  928. var pred parser.Expr
  929. if len(appl) > 0 {
  930. pred = combineAND(appl)
  931. }
  932. rows = inlineJoin(rows, rightRows, pred)
  933. }
  934. } else {
  935. // All tables were pre-joined; start with empty placeholder.
  936. rows = []storage.Row{{}}
  937. }
  938. // Integrate virtual (pre-joined) units into the result.
  939. for _, vu := range virtuals {
  940. for idx := range vu.tableIdxs {
  941. seenTables[idx] = true
  942. }
  943. appl, still := applyWhenSeen(seenTables, remaining)
  944. remaining = still
  945. var pred parser.Expr
  946. if len(appl) > 0 {
  947. pred = combineAND(appl)
  948. }
  949. rows = inlineJoin(rows, vu.rows, pred)
  950. }
  951. // Apply any remaining conditions (shouldn't normally happen).
  952. if len(remaining) > 0 {
  953. pred := combineAND(remaining)
  954. var filtered []storage.Row
  955. for _, row := range rows {
  956. val, _ := e.evalExpr(pred, row)
  957. if toBool(val) {
  958. filtered = append(filtered, row)
  959. }
  960. }
  961. rows = filtered
  962. }
  963. // Also cross-join with any JOIN chains within FROM entries (mixed comma+JOIN syntax).
  964. // We cannot use executeJoins here because the left rows already have qualified keys
  965. // from the isMultiTable cross-join; re-aliasing the left side would corrupt them.
  966. for _, tref := range stmt.From {
  967. join := tref.Join
  968. for join != nil && join.Table != nil {
  969. rightRef := join.Table
  970. rightRows, rerr := e.session.Select(rightRef.Name, nil)
  971. if rerr != nil {
  972. return nil, rerr
  973. }
  974. rightAlias := rightRef.Alias
  975. if rightAlias == "" {
  976. rightAlias = rightRef.Name
  977. }
  978. rightSchema, _ := e.schema.GetSchema(rightRef.Name)
  979. for j := range rightRows {
  980. normalizeRowBySchema(rightRows[j], rightSchema)
  981. rightRows[j] = e.addTableAlias(rightRows[j], rightAlias)
  982. }
  983. var joined []storage.Row
  984. for _, l := range rows {
  985. for _, r := range rightRows {
  986. m := make(storage.Row, len(l)+len(r))
  987. for k, v := range l {
  988. m[k] = v
  989. }
  990. for k, v := range r {
  991. if _, exists := m[k]; !exists {
  992. m[k] = v
  993. } else if strings.Contains(k, ".") {
  994. m[k] = v // qualified keys from right always win
  995. }
  996. }
  997. if join.Condition != nil {
  998. val, _ := e.evalExpr(join.Condition, m)
  999. if !toBool(val) {
  1000. continue
  1001. }
  1002. }
  1003. joined = append(joined, m)
  1004. }
  1005. }
  1006. rows = joined
  1007. join = rightRef.Join
  1008. }
  1009. }
  1010. }
  1011. // Handle GROUP BY
  1012. if len(stmt.GroupBy) > 0 {
  1013. return e.executeGroupBy(stmt, rows, schema)
  1014. }
  1015. // Check for aggregate functions without GROUP BY
  1016. hasAggregate := e.hasAggregates(stmt.Columns)
  1017. if hasAggregate {
  1018. return e.executeAggregateSelect(stmt, rows, schema)
  1019. }
  1020. // Apply ORDER BY, LIMIT, and OFFSET.
  1021. rows = e.orderAndLimitRows(rows, stmt.OrderBy, stmt.Limit, stmt.Offset, stmt.Columns)
  1022. // Build result
  1023. result := NewResult("SELECT")
  1024. // For multi-table or JOIN queries, collect all table refs for SELECT * expansion.
  1025. hasJoin := len(stmt.From) > 0 && stmt.From[0].Join != nil
  1026. allTableRefs := collectAllTableRefs(stmt.From)
  1027. // Resolve qualified wildcard (table.*) projections once, keyed by qualifier.
  1028. type starProjection struct {
  1029. cols []storage.Column
  1030. prefix string
  1031. }
  1032. tableStars := make(map[string]starProjection)
  1033. for _, col := range stmt.Columns {
  1034. if col.TableStar == "" {
  1035. continue
  1036. }
  1037. key := strings.ToUpper(col.TableStar)
  1038. if _, ok := tableStars[key]; ok {
  1039. continue
  1040. }
  1041. cols, prefix, err := e.resolveTableStar(stmt.From, col.TableStar)
  1042. if err != nil {
  1043. return nil, err
  1044. }
  1045. tableStars[key] = starProjection{cols: cols, prefix: prefix}
  1046. }
  1047. // Determine columns
  1048. for i, col := range stmt.Columns {
  1049. if col.Alias != "" {
  1050. result.AddColumn(col.Alias)
  1051. } else if ref, ok := col.Expr.(*parser.ColumnRef); ok {
  1052. result.AddColumn(ref.Column)
  1053. } else if col.Star {
  1054. if isMultiTable || hasJoin {
  1055. // Add columns from ALL joined tables in order
  1056. for _, tref := range allTableRefs {
  1057. sch, _ := e.schema.GetSchema(tref.Name)
  1058. if sch != nil {
  1059. for _, c := range sch.Columns {
  1060. result.AddColumn(c.Name)
  1061. }
  1062. }
  1063. }
  1064. } else {
  1065. // Handle SELECT * - add all columns from schema
  1066. for _, c := range schema.Columns {
  1067. result.AddColumn(c.Name)
  1068. }
  1069. }
  1070. } else if col.TableStar != "" {
  1071. proj := tableStars[strings.ToUpper(col.TableStar)]
  1072. for _, c := range proj.cols {
  1073. result.AddColumn(c.Name)
  1074. }
  1075. } else {
  1076. result.AddColumn(fmt.Sprintf("column%d", i+1))
  1077. }
  1078. }
  1079. // Populate column types from schema metadata for single-table projections so
  1080. // protocol consumers can decode typed values (e.g. timestamps) even when the
  1081. // result set is empty. Join and multi-table projections defer type metadata.
  1082. if !isMultiTable && !hasJoin {
  1083. result.ColumnTypes = selectColumnTypes(stmt, schema)
  1084. }
  1085. // Add rows - evaluate each select expression
  1086. for _, row := range rows {
  1087. values := make([]interface{}, 0)
  1088. for _, col := range stmt.Columns {
  1089. if col.Star {
  1090. if isMultiTable || hasJoin {
  1091. // For multi-table SELECT *, extract columns using qualified names
  1092. for _, tref := range allTableRefs {
  1093. sch, _ := e.schema.GetSchema(tref.Name)
  1094. if sch != nil {
  1095. for _, c := range sch.Columns {
  1096. qualKey := tref.Alias + "." + c.Name
  1097. val, ok := row[qualKey]
  1098. if !ok {
  1099. val = row[c.Name]
  1100. }
  1101. values = append(values, val)
  1102. }
  1103. }
  1104. }
  1105. } else {
  1106. // For SELECT *, add all columns in order. A real column named
  1107. // oid/rowid/_rowid_ is an ordinary column here, not the hidden
  1108. // rowid alias, so use its own value key.
  1109. for _, c := range schema.Columns {
  1110. values = append(values, row[c.Name])
  1111. }
  1112. }
  1113. } else if col.TableStar != "" {
  1114. // Qualified wildcard (table.*): emit only that table's columns,
  1115. // resolving values via the effective alias, falling back to the
  1116. // unqualified key for single-table queries without an alias.
  1117. proj := tableStars[strings.ToUpper(col.TableStar)]
  1118. for _, c := range proj.cols {
  1119. val, ok := row[proj.prefix+"."+c.Name]
  1120. if !ok {
  1121. val = row[c.Name]
  1122. }
  1123. values = append(values, val)
  1124. }
  1125. } else {
  1126. // Evaluate the expression
  1127. val, err := e.evalExpr(col.Expr, row)
  1128. if err != nil {
  1129. return nil, err
  1130. }
  1131. values = append(values, val)
  1132. }
  1133. }
  1134. result.AddRow(values...)
  1135. }
  1136. // Apply DISTINCT if specified
  1137. if stmt.Distinct {
  1138. result.Rows = e.applyDistinct(result.Rows)
  1139. result.RowCount = len(result.Rows)
  1140. }
  1141. return result, nil
  1142. }
  1143. // executeCompound executes a compound SELECT (UNION / UNION ALL / INTERSECT / EXCEPT).
  1144. func (e *Executor) executeCompound(c *parser.CompoundSelect) (*Result, error) {
  1145. left, err := e.executeSelect(c.Left)
  1146. if err != nil {
  1147. return nil, err
  1148. }
  1149. right, err := e.executeSelect(c.Right)
  1150. if err != nil {
  1151. return nil, err
  1152. }
  1153. rowKey := func(row []interface{}) string {
  1154. parts := make([]string, len(row))
  1155. for i, v := range row {
  1156. if v == nil {
  1157. parts[i] = "\x00NULL"
  1158. } else {
  1159. parts[i] = fmt.Sprintf("%v", v)
  1160. }
  1161. }
  1162. return strings.Join(parts, "\x01")
  1163. }
  1164. result := NewResult("SELECT")
  1165. for _, col := range left.Columns {
  1166. result.AddColumn(col)
  1167. }
  1168. switch c.Op {
  1169. case parser.SetOpUnion:
  1170. seen := map[string]bool{}
  1171. for _, row := range left.Rows {
  1172. k := rowKey(row)
  1173. if !seen[k] {
  1174. seen[k] = true
  1175. result.AddRow(row...)
  1176. }
  1177. }
  1178. for _, row := range right.Rows {
  1179. k := rowKey(row)
  1180. if !seen[k] {
  1181. seen[k] = true
  1182. result.AddRow(row...)
  1183. }
  1184. }
  1185. case parser.SetOpUnionAll:
  1186. for _, row := range left.Rows {
  1187. result.AddRow(row...)
  1188. }
  1189. for _, row := range right.Rows {
  1190. result.AddRow(row...)
  1191. }
  1192. case parser.SetOpIntersect:
  1193. rightSet := map[string]bool{}
  1194. for _, row := range right.Rows {
  1195. rightSet[rowKey(row)] = true
  1196. }
  1197. seen := map[string]bool{}
  1198. for _, row := range left.Rows {
  1199. k := rowKey(row)
  1200. if rightSet[k] && !seen[k] {
  1201. seen[k] = true
  1202. result.AddRow(row...)
  1203. }
  1204. }
  1205. case parser.SetOpExcept:
  1206. rightSet := map[string]bool{}
  1207. for _, row := range right.Rows {
  1208. rightSet[rowKey(row)] = true
  1209. }
  1210. seen := map[string]bool{}
  1211. for _, row := range left.Rows {
  1212. k := rowKey(row)
  1213. if !rightSet[k] && !seen[k] {
  1214. seen[k] = true
  1215. result.AddRow(row...)
  1216. }
  1217. }
  1218. }
  1219. // Apply compound-level ORDER BY / LIMIT / OFFSET if present.
  1220. if len(c.OrderBy) > 0 {
  1221. e.sortResultRows(result, c.OrderBy, nil, nil)
  1222. }
  1223. if c.Limit != nil {
  1224. limitVal, err := e.evalExpr(c.Limit, nil)
  1225. if err == nil {
  1226. limit := int(toFloat(limitVal))
  1227. if limit < len(result.Rows) {
  1228. result.Rows = result.Rows[:limit]
  1229. }
  1230. }
  1231. }
  1232. if c.Offset != nil {
  1233. offsetVal, err := e.evalExpr(c.Offset, nil)
  1234. if err == nil {
  1235. offset := int(toFloat(offsetVal))
  1236. if offset >= len(result.Rows) {
  1237. result.Rows = nil
  1238. } else if offset > 0 {
  1239. result.Rows = result.Rows[offset:]
  1240. }
  1241. }
  1242. }
  1243. return result, nil
  1244. }
  1245. // executeSelectExpr executes a SELECT without FROM.
  1246. func (e *Executor) executeSelectExpr(stmt *parser.SelectStmt) (*Result, error) {
  1247. // If any column contains an aggregate, treat as single-group aggregate over one implicit row.
  1248. if e.hasAggregates(stmt.Columns) {
  1249. return e.executeAggregateSelect(stmt, []storage.Row{{}}, nil)
  1250. }
  1251. result := NewResult("SELECT")
  1252. // Determine columns
  1253. for i, col := range stmt.Columns {
  1254. if col.Alias != "" {
  1255. result.AddColumn(col.Alias)
  1256. } else {
  1257. result.AddColumn(fmt.Sprintf("column%d", i+1))
  1258. }
  1259. }
  1260. // Evaluate expressions
  1261. values := make([]interface{}, len(stmt.Columns))
  1262. for i, col := range stmt.Columns {
  1263. val, err := e.evalExpr(col.Expr, nil)
  1264. if err != nil {
  1265. return nil, err
  1266. }
  1267. values[i] = val
  1268. }
  1269. result.AddRow(values...)
  1270. return result, nil
  1271. }
  1272. // executeSelectFromSubquery executes a SELECT with a subquery in FROM clause.
  1273. func (e *Executor) executeSelectFromSubquery(stmt *parser.SelectStmt) (*Result, error) {
  1274. // Execute the subquery to get the derived table
  1275. subqueryResult, err := e.executeSelect(stmt.From[0].Subquery)
  1276. if err != nil {
  1277. return nil, fmt.Errorf("subquery error: %w", err)
  1278. }
  1279. // Convert subquery result to rows for further processing
  1280. derivedRows := make([]storage.Row, 0, subqueryResult.RowCount)
  1281. for _, rowValues := range subqueryResult.Rows {
  1282. row := make(storage.Row)
  1283. for i, col := range subqueryResult.Columns {
  1284. row[col] = rowValues[i]
  1285. }
  1286. derivedRows = append(derivedRows, row)
  1287. }
  1288. // Handle JOINs if present
  1289. if stmt.From[0].Join != nil {
  1290. derivedRows, err = e.executeJoin(stmt.From[0], derivedRows)
  1291. if err != nil {
  1292. return nil, err
  1293. }
  1294. }
  1295. // Apply WHERE clause on derived table
  1296. if stmt.Where != nil {
  1297. filteredRows := make([]storage.Row, 0)
  1298. for _, row := range derivedRows {
  1299. val, err := e.evalExpr(stmt.Where, row)
  1300. if err != nil {
  1301. continue
  1302. }
  1303. if toBool(val) {
  1304. filteredRows = append(filteredRows, row)
  1305. }
  1306. }
  1307. derivedRows = filteredRows
  1308. }
  1309. // Handle GROUP BY
  1310. if len(stmt.GroupBy) > 0 {
  1311. // Create a temporary schema from subquery columns
  1312. tempSchema := &storage.Schema{
  1313. Name: "derived",
  1314. Columns: make([]storage.Column, len(subqueryResult.Columns)),
  1315. }
  1316. for i, col := range subqueryResult.Columns {
  1317. tempSchema.Columns[i] = storage.Column{
  1318. Name: col,
  1319. Type: "ANY",
  1320. }
  1321. }
  1322. return e.executeGroupBy(stmt, derivedRows, tempSchema)
  1323. }
  1324. // Check for aggregate functions without GROUP BY
  1325. hasAggregate := e.hasAggregates(stmt.Columns)
  1326. if hasAggregate {
  1327. tempSchema := &storage.Schema{
  1328. Name: "derived",
  1329. Columns: make([]storage.Column, len(subqueryResult.Columns)),
  1330. }
  1331. for i, col := range subqueryResult.Columns {
  1332. tempSchema.Columns[i] = storage.Column{
  1333. Name: col,
  1334. Type: "ANY",
  1335. }
  1336. }
  1337. return e.executeAggregateSelect(stmt, derivedRows, tempSchema)
  1338. }
  1339. // Apply ORDER BY, LIMIT, and OFFSET.
  1340. derivedRows = e.orderAndLimitRows(derivedRows, stmt.OrderBy, stmt.Limit, stmt.Offset, stmt.Columns)
  1341. // Build result
  1342. result := NewResult("SELECT")
  1343. // Determine output columns
  1344. if stmt.Columns[0].Star {
  1345. // SELECT * from derived table
  1346. for _, col := range subqueryResult.Columns {
  1347. result.AddColumn(col)
  1348. }
  1349. } else {
  1350. // Specific columns
  1351. for _, col := range stmt.Columns {
  1352. if col.Alias != "" {
  1353. result.AddColumn(col.Alias)
  1354. } else if colRef, ok := col.Expr.(*parser.ColumnRef); ok {
  1355. result.AddColumn(colRef.Column)
  1356. } else {
  1357. result.AddColumn("column")
  1358. }
  1359. }
  1360. }
  1361. // Add rows
  1362. for _, row := range derivedRows {
  1363. if stmt.Columns[0].Star {
  1364. // SELECT * - use all columns
  1365. values := make([]interface{}, len(subqueryResult.Columns))
  1366. for i, col := range subqueryResult.Columns {
  1367. values[i] = row[col]
  1368. }
  1369. result.AddRow(values...)
  1370. } else {
  1371. // Specific columns - evaluate expressions
  1372. values := make([]interface{}, len(stmt.Columns))
  1373. for i, col := range stmt.Columns {
  1374. val, err := e.evalExpr(col.Expr, row)
  1375. if err != nil {
  1376. return nil, err
  1377. }
  1378. values[i] = val
  1379. }
  1380. result.AddRow(values...)
  1381. }
  1382. }
  1383. return result, nil
  1384. }
  1385. // executeAggregateSelect executes a SELECT with aggregate functions.
  1386. func (e *Executor) executeAggregateSelect(stmt *parser.SelectStmt, rows []storage.Row, schema *storage.Schema) (*Result, error) {
  1387. result := NewResult("SELECT")
  1388. // Determine columns and evaluate aggregates
  1389. for i, col := range stmt.Columns {
  1390. if col.Alias != "" {
  1391. result.AddColumn(col.Alias)
  1392. } else if col.Star {
  1393. result.AddColumn("*")
  1394. } else {
  1395. result.AddColumn(fmt.Sprintf("column%d", i+1))
  1396. }
  1397. }
  1398. // Calculate values
  1399. values := make([]interface{}, len(stmt.Columns))
  1400. for i, col := range stmt.Columns {
  1401. val, err := e.evalAggregateExpr(col.Expr, rows)
  1402. if err != nil {
  1403. return nil, err
  1404. }
  1405. values[i] = val
  1406. }
  1407. result.AddRow(values...)
  1408. return result, nil
  1409. }
  1410. // executeGroupBy executes a GROUP BY query.
  1411. func (e *Executor) executeGroupBy(stmt *parser.SelectStmt, rows []storage.Row, schema *storage.Schema) (*Result, error) {
  1412. result := NewResult("SELECT")
  1413. // Expand SELECT * if present
  1414. expandedColumns := make([]parser.SelectColumn, 0, len(stmt.Columns))
  1415. for _, col := range stmt.Columns {
  1416. if col.Star {
  1417. for _, c := range schema.Columns {
  1418. expandedColumns = append(expandedColumns, parser.SelectColumn{
  1419. Expr: &parser.ColumnRef{Column: c.Name},
  1420. })
  1421. }
  1422. } else if col.TableStar != "" {
  1423. // Qualified wildcard: expand only the named table's columns.
  1424. cols, prefix, err := e.resolveTableStar(stmt.From, col.TableStar)
  1425. if err != nil {
  1426. return nil, err
  1427. }
  1428. for _, c := range cols {
  1429. expandedColumns = append(expandedColumns, parser.SelectColumn{
  1430. Expr: &parser.ColumnRef{Table: prefix, Column: c.Name},
  1431. })
  1432. }
  1433. } else {
  1434. expandedColumns = append(expandedColumns, col)
  1435. }
  1436. }
  1437. // Determine column names
  1438. columnNames := make([]string, len(expandedColumns))
  1439. for i, col := range expandedColumns {
  1440. if col.Alias != "" {
  1441. columnNames[i] = col.Alias
  1442. result.AddColumn(col.Alias)
  1443. } else if ref, ok := col.Expr.(*parser.ColumnRef); ok {
  1444. columnNames[i] = ref.Column
  1445. result.AddColumn(ref.Column)
  1446. } else {
  1447. columnNames[i] = fmt.Sprintf("column%d", i+1)
  1448. result.AddColumn(columnNames[i])
  1449. }
  1450. }
  1451. // Fast path: use running accumulators instead of collecting rows per group.
  1452. // Applicable when there is no HAVING clause and all aggregate SELECT columns
  1453. // are direct FunctionCalls (COUNT/SUM/AVG/MIN/MAX).
  1454. if e.canUseGroupAccum(stmt, expandedColumns) {
  1455. return e.executeGroupByAccum(stmt, rows, result, expandedColumns, columnNames)
  1456. }
  1457. // Slow path: collect full rows per group then evaluate aggregates over them.
  1458. groups := make(map[string][]storage.Row)
  1459. for _, row := range rows {
  1460. key := e.buildGroupKey(stmt.GroupBy, row)
  1461. groups[key] = append(groups[key], row)
  1462. }
  1463. for _, groupRows := range groups {
  1464. if stmt.Having != nil {
  1465. val, err := e.evalAggregateExpr(stmt.Having, groupRows)
  1466. if err != nil || val == nil || !toBool(val) {
  1467. continue
  1468. }
  1469. }
  1470. values := make([]interface{}, len(expandedColumns))
  1471. for i, col := range expandedColumns {
  1472. if e.isAggregate(col.Expr) {
  1473. val, err := e.evalAggregateExpr(col.Expr, groupRows)
  1474. if err != nil {
  1475. return nil, err
  1476. }
  1477. values[i] = val
  1478. } else {
  1479. val, err := e.evalExpr(col.Expr, groupRows[0])
  1480. if err != nil {
  1481. return nil, err
  1482. }
  1483. values[i] = val
  1484. }
  1485. }
  1486. result.AddRow(values...)
  1487. }
  1488. return e.finalizeGroupResult(stmt, result, expandedColumns, columnNames)
  1489. }
  1490. // canUseGroupAccum returns true when the fast accumulator path can handle the query.
  1491. func (e *Executor) canUseGroupAccum(stmt *parser.SelectStmt, expandedColumns []parser.SelectColumn) bool {
  1492. if stmt.Having != nil {
  1493. return false
  1494. }
  1495. for _, col := range expandedColumns {
  1496. if !e.isAggregate(col.Expr) {
  1497. continue
  1498. }
  1499. fn, ok := col.Expr.(*parser.FunctionCall)
  1500. if !ok {
  1501. return false
  1502. }
  1503. switch strings.ToUpper(fn.Name) {
  1504. case "COUNT", "SUM", "AVG", "MIN", "MAX":
  1505. default:
  1506. return false
  1507. }
  1508. }
  1509. return true
  1510. }
  1511. // aggColInfo pairs a SELECT column index with its aggregate FunctionCall.
  1512. type aggColInfo struct {
  1513. colIdx int
  1514. fn *parser.FunctionCall
  1515. }
  1516. // aggAccum holds running state for a single aggregate function.
  1517. type aggAccum struct {
  1518. count int64
  1519. sumI int64
  1520. sumF float64
  1521. allInt bool
  1522. hasVal bool
  1523. extreme interface{}
  1524. seen map[interface{}]struct{} // for DISTINCT
  1525. }
  1526. // groupAccumState holds per-group state for the fast accumulator path.
  1527. type groupAccumState struct {
  1528. firstRow storage.Row
  1529. accums []*aggAccum
  1530. }
  1531. // executeGroupByAccum is the fast GROUP BY path: increments per-group counters as rows
  1532. // arrive rather than materialising row slices, keeping O(1) state per group.
  1533. func (e *Executor) executeGroupByAccum(stmt *parser.SelectStmt, rows []storage.Row, result *Result, expandedColumns []parser.SelectColumn, columnNames []string) (*Result, error) {
  1534. var aggCols []aggColInfo
  1535. for i, col := range expandedColumns {
  1536. if e.isAggregate(col.Expr) {
  1537. aggCols = append(aggCols, aggColInfo{i, col.Expr.(*parser.FunctionCall)})
  1538. }
  1539. }
  1540. states := make(map[string]*groupAccumState, 64)
  1541. var keyOrder []string
  1542. for _, row := range rows {
  1543. key := e.buildGroupKey(stmt.GroupBy, row)
  1544. state, exists := states[key]
  1545. if !exists {
  1546. accums := make([]*aggAccum, len(aggCols))
  1547. for j, ac := range aggCols {
  1548. a := &aggAccum{allInt: true}
  1549. if ac.fn.Distinct {
  1550. a.seen = make(map[interface{}]struct{})
  1551. }
  1552. accums[j] = a
  1553. }
  1554. state = &groupAccumState{firstRow: row, accums: accums}
  1555. states[key] = state
  1556. keyOrder = append(keyOrder, key)
  1557. }
  1558. for j, ac := range aggCols {
  1559. e.feedAggAccum(state.accums[j], ac.fn, row)
  1560. }
  1561. }
  1562. for _, key := range keyOrder {
  1563. state := states[key]
  1564. values := make([]interface{}, len(expandedColumns))
  1565. for i, col := range expandedColumns {
  1566. if e.isAggregate(col.Expr) {
  1567. for j, ac := range aggCols {
  1568. if ac.colIdx == i {
  1569. values[i] = finalizeAggAccum(state.accums[j], ac.fn)
  1570. break
  1571. }
  1572. }
  1573. } else {
  1574. val, _ := e.evalExpr(col.Expr, state.firstRow)
  1575. values[i] = val
  1576. }
  1577. }
  1578. result.AddRow(values...)
  1579. }
  1580. return e.finalizeGroupResult(stmt, result, expandedColumns, columnNames)
  1581. }
  1582. // feedAggAccum updates a running accumulator with one row.
  1583. func (e *Executor) feedAggAccum(a *aggAccum, fn *parser.FunctionCall, row storage.Row) {
  1584. switch strings.ToUpper(fn.Name) {
  1585. case "COUNT":
  1586. if fn.Star {
  1587. a.count++
  1588. return
  1589. }
  1590. if len(fn.Args) == 0 {
  1591. return
  1592. }
  1593. val, _ := e.evalExpr(fn.Args[0], row)
  1594. if val == nil {
  1595. return
  1596. }
  1597. if fn.Distinct {
  1598. k := fmt.Sprintf("%v", val)
  1599. if _, exists := a.seen[k]; exists {
  1600. return
  1601. }
  1602. a.seen[k] = struct{}{}
  1603. }
  1604. a.count++
  1605. case "SUM":
  1606. if len(fn.Args) == 0 {
  1607. return
  1608. }
  1609. val, _ := e.evalExpr(fn.Args[0], row)
  1610. if val == nil {
  1611. return
  1612. }
  1613. if fn.Distinct {
  1614. k := fmt.Sprintf("%v", val)
  1615. if _, exists := a.seen[k]; exists {
  1616. return
  1617. }
  1618. a.seen[k] = struct{}{}
  1619. }
  1620. if isIntVal(val) {
  1621. a.sumI += toInt64(val)
  1622. } else {
  1623. a.allInt = false
  1624. a.sumF += toFloat(val)
  1625. }
  1626. a.hasVal = true
  1627. case "AVG":
  1628. if len(fn.Args) == 0 {
  1629. return
  1630. }
  1631. val, _ := e.evalExpr(fn.Args[0], row)
  1632. if val == nil {
  1633. return
  1634. }
  1635. a.sumF += toFloat(val)
  1636. a.count++
  1637. a.hasVal = true
  1638. case "MIN":
  1639. if len(fn.Args) == 0 {
  1640. return
  1641. }
  1642. val, _ := e.evalExpr(fn.Args[0], row)
  1643. if val != nil && (a.extreme == nil || compare(val, a.extreme) < 0) {
  1644. a.extreme = val
  1645. }
  1646. case "MAX":
  1647. if len(fn.Args) == 0 {
  1648. return
  1649. }
  1650. val, _ := e.evalExpr(fn.Args[0], row)
  1651. if val != nil && (a.extreme == nil || compare(val, a.extreme) > 0) {
  1652. a.extreme = val
  1653. }
  1654. }
  1655. }
  1656. // finalizeAggAccum computes the final aggregate value from a running accumulator.
  1657. func finalizeAggAccum(a *aggAccum, fn *parser.FunctionCall) interface{} {
  1658. switch strings.ToUpper(fn.Name) {
  1659. case "COUNT":
  1660. return a.count
  1661. case "SUM":
  1662. if !a.hasVal {
  1663. return nil
  1664. }
  1665. if a.allInt {
  1666. return a.sumI
  1667. }
  1668. return a.sumF + float64(a.sumI)
  1669. case "AVG":
  1670. if !a.hasVal || a.count == 0 {
  1671. return nil
  1672. }
  1673. return a.sumF / float64(a.count)
  1674. case "MIN", "MAX":
  1675. return a.extreme
  1676. }
  1677. return nil
  1678. }
  1679. // finalizeGroupResult applies DISTINCT, ORDER BY, and LIMIT/OFFSET to a GROUP BY result.
  1680. func (e *Executor) finalizeGroupResult(stmt *parser.SelectStmt, result *Result, expandedColumns []parser.SelectColumn, columnNames []string) (*Result, error) {
  1681. if stmt.Distinct {
  1682. result.Rows = e.applyDistinct(result.Rows)
  1683. }
  1684. e.orderAndLimitResultRows(result, stmt.OrderBy, stmt.Limit, stmt.Offset, expandedColumns, columnNames)
  1685. return result, nil
  1686. }
  1687. // executeJoins recursively processes all JOIN clauses in a table reference.
  1688. func (e *Executor) executeJoins(tableRef parser.TableRef, leftRows []storage.Row) ([]storage.Row, error) {
  1689. return e.executeJoinsWithMode(tableRef, leftRows, true)
  1690. }
  1691. func (e *Executor) executeJoinsWithMode(tableRef parser.TableRef, leftRows []storage.Row, qualifyLeft bool) ([]storage.Row, error) {
  1692. if tableRef.Join == nil || tableRef.Join.Table == nil {
  1693. return leftRows, nil
  1694. }
  1695. // Get the right table name. Equality joins against its primary key can probe
  1696. // only the referenced rows instead of scanning the whole table.
  1697. rightTableRef := tableRef.Join.Table
  1698. rightTable := rightTableRef.Name
  1699. // Perform the join between left and right
  1700. var result []storage.Row
  1701. leftTableName := tableRef.Name
  1702. leftAlias := tableRef.Alias
  1703. rightAlias := rightTableRef.Alias
  1704. // If leftAlias is empty, use the table name
  1705. if leftAlias == "" {
  1706. leftAlias = leftTableName
  1707. }
  1708. if rightAlias == "" {
  1709. rightAlias = rightTable
  1710. }
  1711. leftAliasForMerge := leftAlias
  1712. if !qualifyLeft {
  1713. leftAliasForMerge = ""
  1714. }
  1715. // Build a synthetic TableRef so we can reuse extractEqualityJoinKeys.
  1716. syntheticLeft := parser.TableRef{Name: leftTableName, Alias: leftAlias}
  1717. syntheticJoin := &parser.JoinClause{
  1718. Type: tableRef.Join.Type,
  1719. Table: &parser.TableRef{Name: rightTable, Alias: rightAlias},
  1720. Condition: tableRef.Join.Condition,
  1721. }
  1722. leftKey, rightKey, canHash := extractEqualityJoinKeys(tableRef.Join.Condition, syntheticLeft, syntheticJoin)
  1723. rightSchema, err := e.schema.GetSchema(rightTable)
  1724. if err != nil {
  1725. return nil, err
  1726. }
  1727. var rightRows []storage.Row
  1728. if canHash && strings.EqualFold(rightSchema.PrimaryKey, rightKey) && len(leftRows) <= 256 {
  1729. seen := make(map[string]bool, len(leftRows))
  1730. for _, left := range leftRows {
  1731. key := joinKeyString(left, leftKey)
  1732. if key == "\x00" || seen[key] {
  1733. continue
  1734. }
  1735. seen[key] = true
  1736. row, getErr := e.session.GetByPK(rightTable, key)
  1737. if getErr == storage.ErrKeyNotFound {
  1738. continue
  1739. }
  1740. if getErr != nil {
  1741. return nil, getErr
  1742. }
  1743. normalizeRowBySchema(row, rightSchema)
  1744. rightRows = append(rightRows, row)
  1745. }
  1746. } else {
  1747. rightRows, err = e.session.Select(rightTable, nil)
  1748. if err != nil {
  1749. return nil, err
  1750. }
  1751. for _, row := range rightRows {
  1752. normalizeRowBySchema(row, rightSchema)
  1753. }
  1754. }
  1755. switch tableRef.Join.Type {
  1756. case parser.JoinInner:
  1757. if canHash {
  1758. hashTable := make(map[string][]storage.Row, len(rightRows))
  1759. for _, right := range rightRows {
  1760. k := joinKeyString(right, rightKey)
  1761. hashTable[k] = append(hashTable[k], right)
  1762. }
  1763. for _, left := range leftRows {
  1764. k := joinKeyString(left, leftKey)
  1765. for _, right := range hashTable[k] {
  1766. result = append(result, e.mergeRows(left, right, leftAliasForMerge, rightAlias))
  1767. }
  1768. }
  1769. } else {
  1770. for _, left := range leftRows {
  1771. for _, right := range rightRows {
  1772. merged := e.mergeRows(left, right, leftAliasForMerge, rightAlias)
  1773. if tableRef.Join.Condition != nil {
  1774. match, _ := e.evalExpr(tableRef.Join.Condition, merged)
  1775. if toBool(match) {
  1776. result = append(result, merged)
  1777. }
  1778. } else {
  1779. result = append(result, merged)
  1780. }
  1781. }
  1782. }
  1783. }
  1784. case parser.JoinLeft:
  1785. if canHash {
  1786. hashTable := make(map[string][]storage.Row, len(rightRows))
  1787. for _, right := range rightRows {
  1788. k := joinKeyString(right, rightKey)
  1789. hashTable[k] = append(hashTable[k], right)
  1790. }
  1791. nullRight := makeNullRow(rightRows, rightTable, e)
  1792. for _, left := range leftRows {
  1793. k := joinKeyString(left, leftKey)
  1794. matches := hashTable[k]
  1795. if len(matches) == 0 {
  1796. result = append(result, e.mergeRows(left, nullRight, leftAliasForMerge, rightAlias))
  1797. } else {
  1798. for _, right := range matches {
  1799. result = append(result, e.mergeRows(left, right, leftAliasForMerge, rightAlias))
  1800. }
  1801. }
  1802. }
  1803. } else {
  1804. for _, left := range leftRows {
  1805. matched := false
  1806. for _, right := range rightRows {
  1807. merged := e.mergeRows(left, right, leftAliasForMerge, rightAlias)
  1808. if tableRef.Join.Condition != nil {
  1809. match, _ := e.evalExpr(tableRef.Join.Condition, merged)
  1810. if toBool(match) {
  1811. result = append(result, merged)
  1812. matched = true
  1813. }
  1814. }
  1815. }
  1816. if !matched {
  1817. nullRight := makeNullRow(rightRows, rightTable, e)
  1818. result = append(result, e.mergeRows(left, nullRight, leftAliasForMerge, rightAlias))
  1819. }
  1820. }
  1821. }
  1822. case parser.JoinCross:
  1823. for _, left := range leftRows {
  1824. for _, right := range rightRows {
  1825. result = append(result, e.mergeRows(left, right, leftAliasForMerge, rightAlias))
  1826. }
  1827. }
  1828. }
  1829. // Recursively process any additional joins
  1830. if rightTableRef.Join != nil {
  1831. return e.executeJoinsWithMode(*rightTableRef, result, false)
  1832. }
  1833. return result, nil
  1834. }
  1835. // executeJoin executes a JOIN operation.
  1836. func (e *Executor) executeJoin(tableRef parser.TableRef, leftRows []storage.Row) ([]storage.Row, error) {
  1837. join := tableRef.Join
  1838. if join == nil || join.Table == nil {
  1839. return leftRows, nil
  1840. }
  1841. rightTable := join.Table.Name
  1842. rightRows, err := e.session.Select(rightTable, nil)
  1843. if err != nil {
  1844. return nil, err
  1845. }
  1846. var result []storage.Row
  1847. switch join.Type {
  1848. case parser.JoinInner:
  1849. leftKey, rightKey, canHash := extractEqualityJoinKeys(join.Condition, tableRef, join)
  1850. if canHash {
  1851. // Hash join: build phase on right, probe phase on left — O(N+M) vs O(N*M)
  1852. hashTable := make(map[string][]storage.Row, len(rightRows))
  1853. for _, right := range rightRows {
  1854. k := joinKeyString(right, rightKey)
  1855. hashTable[k] = append(hashTable[k], right)
  1856. }
  1857. for _, left := range leftRows {
  1858. k := joinKeyString(left, leftKey)
  1859. for _, right := range hashTable[k] {
  1860. result = append(result, e.mergeRows(left, right, tableRef.Alias, join.Table.Alias))
  1861. }
  1862. }
  1863. } else {
  1864. for _, left := range leftRows {
  1865. for _, right := range rightRows {
  1866. merged := e.mergeRows(left, right, tableRef.Alias, join.Table.Alias)
  1867. if join.Condition != nil {
  1868. match, _ := e.evalExpr(join.Condition, merged)
  1869. if toBool(match) {
  1870. result = append(result, merged)
  1871. }
  1872. } else {
  1873. result = append(result, merged)
  1874. }
  1875. }
  1876. }
  1877. }
  1878. case parser.JoinLeft:
  1879. leftKey, rightKey, canHash := extractEqualityJoinKeys(join.Condition, tableRef, join)
  1880. if canHash {
  1881. hashTable := make(map[string][]storage.Row, len(rightRows))
  1882. for _, right := range rightRows {
  1883. k := joinKeyString(right, rightKey)
  1884. hashTable[k] = append(hashTable[k], right)
  1885. }
  1886. nullRight := makeNullRow(rightRows, rightTable, e)
  1887. for _, left := range leftRows {
  1888. k := joinKeyString(left, leftKey)
  1889. matches := hashTable[k]
  1890. if len(matches) == 0 {
  1891. result = append(result, e.mergeRows(left, nullRight, tableRef.Alias, join.Table.Alias))
  1892. } else {
  1893. for _, right := range matches {
  1894. result = append(result, e.mergeRows(left, right, tableRef.Alias, join.Table.Alias))
  1895. }
  1896. }
  1897. }
  1898. } else {
  1899. for _, left := range leftRows {
  1900. matched := false
  1901. for _, right := range rightRows {
  1902. merged := e.mergeRows(left, right, tableRef.Alias, join.Table.Alias)
  1903. if join.Condition != nil {
  1904. match, _ := e.evalExpr(join.Condition, merged)
  1905. if toBool(match) {
  1906. result = append(result, merged)
  1907. matched = true
  1908. }
  1909. }
  1910. }
  1911. if !matched {
  1912. nullRight := makeNullRow(rightRows, rightTable, e)
  1913. result = append(result, e.mergeRows(left, nullRight, tableRef.Alias, join.Table.Alias))
  1914. }
  1915. }
  1916. }
  1917. case parser.JoinCross:
  1918. for _, left := range leftRows {
  1919. for _, right := range rightRows {
  1920. result = append(result, e.mergeRows(left, right, tableRef.Alias, join.Table.Alias))
  1921. }
  1922. }
  1923. }
  1924. return result, nil
  1925. }
  1926. // extractEqualityJoinKeys checks if a JOIN condition is a simple col = col equality
  1927. // and returns the key names to probe in left rows and build from right rows.
  1928. func extractEqualityJoinKeys(condition parser.Expr, leftRef parser.TableRef, join *parser.JoinClause) (leftKey, rightKey string, ok bool) {
  1929. if condition == nil {
  1930. return "", "", false
  1931. }
  1932. bin, isBin := condition.(*parser.BinaryExpr)
  1933. if !isBin || bin.Op != lexer.TokenEq {
  1934. return "", "", false
  1935. }
  1936. lRef, leftIsCol := bin.Left.(*parser.ColumnRef)
  1937. rRef, rightIsCol := bin.Right.(*parser.ColumnRef)
  1938. if !leftIsCol || !rightIsCol {
  1939. return "", "", false
  1940. }
  1941. leftAlias := leftRef.Alias
  1942. leftName := leftRef.Name
  1943. rightAlias := join.Table.Alias
  1944. rightName := join.Table.Name
  1945. leftJoinKey := func(r *parser.ColumnRef) (string, bool) {
  1946. if r.Table == "" || r.Table == leftAlias || r.Table == leftName {
  1947. return r.Column, true
  1948. }
  1949. // In a chained explicit JOIN, the left row already contains every table
  1950. // joined so far. Preserve qualified references such as "o.id" so joins
  1951. // against earlier tables can still use the hash path.
  1952. if r.Table != rightAlias && r.Table != rightName {
  1953. return r.Table + "." + r.Column, true
  1954. }
  1955. return "", false
  1956. }
  1957. rightJoinKey := func(r *parser.ColumnRef) (string, bool) {
  1958. if r.Table == "" || r.Table == rightAlias || r.Table == rightName {
  1959. return r.Column, true
  1960. }
  1961. return "", false
  1962. }
  1963. if lk, leftOK := leftJoinKey(lRef); leftOK {
  1964. if rk, rightOK := rightJoinKey(rRef); rightOK {
  1965. return lk, rk, true
  1966. }
  1967. }
  1968. if lk, leftOK := leftJoinKey(rRef); leftOK {
  1969. if rk, rightOK := rightJoinKey(lRef); rightOK {
  1970. return lk, rk, true
  1971. }
  1972. }
  1973. return "", "", false
  1974. }
  1975. // joinKeyString returns a string representation of a row's join key for hashing.
  1976. func joinKeyString(row storage.Row, col string) string {
  1977. if v, ok := row[col]; ok {
  1978. return fmt.Sprintf("%v", v)
  1979. }
  1980. return "\x00"
  1981. }
  1982. // makeNullRow builds a null-valued row based on the right table's rows or schema.
  1983. func makeNullRow(rightRows []storage.Row, rightTable string, e *Executor) storage.Row {
  1984. nullRight := make(storage.Row)
  1985. if len(rightRows) > 0 {
  1986. for k := range rightRows[0] {
  1987. nullRight[k] = nil
  1988. }
  1989. } else {
  1990. rightSchema, err := e.schema.GetSchema(rightTable)
  1991. if err == nil {
  1992. for _, col := range rightSchema.Columns {
  1993. nullRight[col.Name] = nil
  1994. }
  1995. }
  1996. }
  1997. return nullRight
  1998. }
  1999. // mergeRows merges two rows with optional table aliases.
  2000. func (e *Executor) mergeRows(left, right storage.Row, leftAlias, rightAlias string) storage.Row {
  2001. result := make(storage.Row)
  2002. for k, v := range left {
  2003. // Copy the key as-is (it might already be qualified)
  2004. result[k] = v
  2005. // Only add qualified name if the key is NOT already qualified and we have an alias
  2006. if leftAlias != "" && !strings.Contains(k, ".") {
  2007. result[leftAlias+"."+k] = v
  2008. }
  2009. }
  2010. for k, v := range right {
  2011. // For unqualified names, only add if they don't already exist
  2012. // This prevents right table columns from overwriting left table columns
  2013. if !strings.Contains(k, ".") {
  2014. if _, exists := result[k]; !exists {
  2015. result[k] = v
  2016. }
  2017. // Add qualified name for right table
  2018. if rightAlias != "" {
  2019. result[rightAlias+"."+k] = v
  2020. }
  2021. } else {
  2022. // Already qualified, just copy it
  2023. result[k] = v
  2024. }
  2025. }
  2026. return result
  2027. }
  2028. // collectAllTableRefs returns a flat list of (alias, tableName) pairs for all tables
  2029. // referenced in a FROM clause, following both implicit (comma) and explicit JOIN chains.
  2030. func collectAllTableRefs(from []parser.TableRef) []parser.TableRef {
  2031. var refs []parser.TableRef
  2032. for _, tref := range from {
  2033. cur := tref
  2034. for {
  2035. // Shallow copy to hold only this table (no join chain)
  2036. flat := parser.TableRef{Name: cur.Name, Alias: cur.Alias}
  2037. if flat.Alias == "" {
  2038. flat.Alias = flat.Name
  2039. }
  2040. refs = append(refs, flat)
  2041. if cur.Join == nil || cur.Join.Table == nil {
  2042. break
  2043. }
  2044. cur = *cur.Join.Table
  2045. }
  2046. }
  2047. return refs
  2048. }
  2049. // resolveTableStar resolves a qualified wildcard (table.*) qualifier to the
  2050. // matching table ref in a FROM clause. It returns the table's schema columns
  2051. // and the key prefix used to look values up in a joined/aliased row (the
  2052. // effective table alias). An unknown qualifier is an error, never a silent
  2053. // fallback to plain column expansion.
  2054. func (e *Executor) resolveTableStar(from []parser.TableRef, qualifier string) ([]storage.Column, string, error) {
  2055. refs := collectAllTableRefs(from)
  2056. for _, ref := range refs {
  2057. if strings.EqualFold(ref.Alias, qualifier) {
  2058. sch, err := e.schema.GetSchema(ref.Name)
  2059. if err != nil {
  2060. return nil, "", err
  2061. }
  2062. return sch.Columns, ref.Alias, nil
  2063. }
  2064. }
  2065. for _, ref := range refs {
  2066. if strings.EqualFold(ref.Name, qualifier) {
  2067. sch, err := e.schema.GetSchema(ref.Name)
  2068. if err != nil {
  2069. return nil, "", err
  2070. }
  2071. return sch.Columns, ref.Alias, nil
  2072. }
  2073. }
  2074. return nil, "", fmt.Errorf("no such table or alias: %s", qualifier)
  2075. }
  2076. // addTableAlias adds table-qualified names to a row.
  2077. // normalizeRowBySchema converts float64 values in integer-affinity columns to int64.
  2078. // This is needed because JSON deserialization always produces float64 for numbers.
  2079. func normalizeRowBySchema(row storage.Row, schema *storage.Schema) {
  2080. if schema == nil {
  2081. return
  2082. }
  2083. for _, col := range schema.Columns {
  2084. upper := strings.ToUpper(col.Type)
  2085. isInt := strings.Contains(upper, "INT") || upper == "BOOLEAN" || upper == "BOOL"
  2086. if !isInt {
  2087. continue
  2088. }
  2089. if f, ok := row[col.Name].(float64); ok {
  2090. row[col.Name] = int64(f)
  2091. }
  2092. }
  2093. }
  2094. func (e *Executor) addTableAlias(row storage.Row, alias string) storage.Row {
  2095. result := make(storage.Row)
  2096. for k, v := range row {
  2097. result[k] = v
  2098. // Don't add alias to already-qualified names
  2099. if !strings.Contains(k, ".") {
  2100. result[alias+"."+k] = v
  2101. }
  2102. }
  2103. return result
  2104. }
  2105. // executeInsert executes an INSERT statement.
  2106. func (e *Executor) executeInsert(stmt *parser.InsertStmt) (*Result, error) {
  2107. tableName := stmt.Table.Name
  2108. schema, err := e.schema.GetSchema(tableName)
  2109. if err != nil {
  2110. return nil, err
  2111. }
  2112. // INSERT ... SELECT: materialise the SELECT result and bulk-insert.
  2113. if stmt.Select != nil {
  2114. sel, err := e.executeSelect(stmt.Select)
  2115. if err != nil {
  2116. return nil, err
  2117. }
  2118. rows := make([]storage.Row, 0, len(sel.Rows))
  2119. for _, selRow := range sel.Rows {
  2120. row := make(storage.Row)
  2121. if len(stmt.Columns) > 0 {
  2122. for i, col := range stmt.Columns {
  2123. if i < len(selRow) {
  2124. row[col] = selRow[i]
  2125. }
  2126. }
  2127. } else {
  2128. for i, col := range schema.Columns {
  2129. if i < len(selRow) {
  2130. row[col.Name] = selRow[i]
  2131. }
  2132. }
  2133. }
  2134. rows = append(rows, row)
  2135. }
  2136. var count int
  2137. var lastRowID int64
  2138. if e.inTransaction {
  2139. for _, row := range rows {
  2140. rid, err := e.session.InsertWithRowID(tableName, row)
  2141. if err != nil {
  2142. return nil, err
  2143. }
  2144. lastRowID = rid
  2145. count++
  2146. }
  2147. } else {
  2148. count, lastRowID, err = e.session.InsertBulkWithLastRowID(tableName, rows)
  2149. }
  2150. if err != nil {
  2151. return nil, err
  2152. }
  2153. result := NewResult("INSERT")
  2154. result.SetRowCount(count)
  2155. result.SetLastInsertID(lastRowID)
  2156. if count > 0 {
  2157. e.lastInsertRowID = lastRowID
  2158. }
  2159. e.recordChanges(int64(count))
  2160. return result, nil
  2161. }
  2162. count := 0
  2163. var lastRowID int64
  2164. err = e.runDMLAtomic(tableName, func() error {
  2165. for _, values := range stmt.Values {
  2166. row := make(storage.Row)
  2167. if len(stmt.Columns) > 0 {
  2168. // Named columns
  2169. for i, col := range stmt.Columns {
  2170. if i < len(values) {
  2171. val, err := e.evalExpr(values[i], nil)
  2172. if err != nil {
  2173. return err
  2174. }
  2175. row[col] = val
  2176. }
  2177. }
  2178. } else {
  2179. // All columns in order
  2180. for i, col := range schema.Columns {
  2181. if i < len(values) {
  2182. val, err := e.evalExpr(values[i], nil)
  2183. if err != nil {
  2184. return err
  2185. }
  2186. row[col.Name] = val
  2187. }
  2188. }
  2189. }
  2190. rowID, err := e.session.InsertWithRowID(tableName, row)
  2191. if err != nil {
  2192. if strings.Contains(err.Error(), "duplicate") && (stmt.ConflictDoNothing || len(stmt.ConflictUpdate) > 0) {
  2193. if stmt.ConflictDoNothing {
  2194. continue
  2195. }
  2196. if len(stmt.ConflictTarget) > 0 && !containsFold(stmt.ConflictTarget, schema.PrimaryKey) {
  2197. return fmt.Errorf("ON CONFLICT target must include primary key %s", schema.PrimaryKey)
  2198. }
  2199. pkValue := row[schema.PrimaryKey]
  2200. updated, updateErr := e.session.UpdateFunc(tableName, func(existing storage.Row) (storage.Row, error) {
  2201. context := e.addTableAlias(existing, tableName)
  2202. updates := make(storage.Row)
  2203. for _, assignment := range stmt.ConflictUpdate {
  2204. value, evalErr := e.evalExpr(assignment.Value, context)
  2205. if evalErr != nil {
  2206. return nil, evalErr
  2207. }
  2208. updates[assignment.Column] = value
  2209. }
  2210. return updates, nil
  2211. }, func(existing storage.Row) bool {
  2212. return fmt.Sprintf("%v", existing[schema.PrimaryKey]) == fmt.Sprintf("%v", pkValue)
  2213. })
  2214. if updateErr != nil {
  2215. return updateErr
  2216. }
  2217. if updated != 1 {
  2218. return fmt.Errorf("ON CONFLICT row disappeared during update")
  2219. }
  2220. count++
  2221. continue
  2222. }
  2223. // Handle conflict based on OnConflict action
  2224. if strings.Contains(err.Error(), "duplicate") {
  2225. switch stmt.OnConflict {
  2226. case parser.ConflictIgnore:
  2227. // Silently ignore the duplicate
  2228. continue
  2229. case parser.ConflictReplace:
  2230. // Delete existing row and insert new one
  2231. pkValue := row[schema.PrimaryKey]
  2232. if pkValue != nil {
  2233. e.session.Delete(tableName, func(r storage.Row) bool {
  2234. return fmt.Sprintf("%v", r[schema.PrimaryKey]) == fmt.Sprintf("%v", pkValue)
  2235. })
  2236. // Try insert again
  2237. replacedID, replaceErr := e.session.InsertWithRowID(tableName, row)
  2238. if replaceErr != nil {
  2239. return replaceErr
  2240. }
  2241. lastRowID = replacedID
  2242. }
  2243. case parser.ConflictAbort, parser.ConflictFail:
  2244. return err
  2245. case parser.ConflictRollback:
  2246. // In a real implementation, this would rollback the transaction
  2247. return err
  2248. default:
  2249. return err
  2250. }
  2251. } else {
  2252. return err
  2253. }
  2254. } else {
  2255. lastRowID = rowID
  2256. }
  2257. count++
  2258. }
  2259. return nil
  2260. })
  2261. if err != nil {
  2262. return nil, err
  2263. }
  2264. result := NewResult("INSERT")
  2265. result.SetRowCount(count)
  2266. result.SetLastInsertID(lastRowID)
  2267. if count > 0 {
  2268. e.lastInsertRowID = lastRowID
  2269. }
  2270. e.recordChanges(int64(count))
  2271. return result, nil
  2272. }
  2273. // recordChanges updates the session-local changes()/total_changes() state after
  2274. // a successful INSERT/UPDATE/DELETE. total_changes() is a monotonic counter of
  2275. // every completed DML statement (SQLite semantics): it is incremented even when
  2276. // the change is later undone by ROLLBACK or ROLLBACK TO, and is never decremented.
  2277. func (e *Executor) recordChanges(affected int64) {
  2278. e.changes = affected
  2279. e.totalChanges += affected
  2280. }
  2281. // runDMLAtomic runs apply, staging the DML in an implicit transaction when the
  2282. // target table carries a UNIQUE index and no explicit transaction is open, so a
  2283. // statement that fails partway (e.g. a multi-row UPDATE/INSERT that hits a unique
  2284. // violation after earlier rows staged) leaves no durable effects — matching
  2285. // SQLite's statement-level atomicity. It commits on success and rolls back on any
  2286. // error. When already in an explicit transaction, apply runs directly and the
  2287. // surrounding COMMIT/ROLLBACK governs durability.
  2288. func (e *Executor) runDMLAtomic(tableName string, apply func() error) error {
  2289. if e.inTransaction {
  2290. return apply()
  2291. }
  2292. uniq, err := e.table.HasUniqueIndex(tableName)
  2293. if err != nil {
  2294. return err
  2295. }
  2296. if !uniq {
  2297. return apply()
  2298. }
  2299. if err := e.session.Begin(); err != nil {
  2300. return err
  2301. }
  2302. if err := apply(); err != nil {
  2303. _ = e.session.Rollback()
  2304. return err
  2305. }
  2306. return e.session.Commit()
  2307. }
  2308. func containsFold(values []string, target string) bool {
  2309. for _, value := range values {
  2310. if strings.EqualFold(value, target) {
  2311. return true
  2312. }
  2313. }
  2314. return false
  2315. }
  2316. // primeSubqueries pre-executes non-correlated subqueries referenced by a
  2317. // statement expression and stores their results in the per-query subquery cache.
  2318. // It runs before the storage session acquires its lock for a scan-based
  2319. // UPDATE/DELETE. Without this, evaluating a predicate such as
  2320. // "WHERE id IN (SELECT ...)" invokes the session recursively while the session
  2321. // lock is held, which deadlocks. The cache is only consulted when there is no
  2322. // outer row (see evalInExpr), so priming is limited to that same non-correlated
  2323. // case.
  2324. func (e *Executor) primeSubqueries(expr parser.Expr) {
  2325. if expr == nil || e.subqueryCache == nil || e.outerRow != nil {
  2326. return
  2327. }
  2328. prime := func(sub *parser.SelectStmt) {
  2329. if sub == nil {
  2330. return
  2331. }
  2332. if _, ok := e.subqueryCache[sub]; ok {
  2333. return
  2334. }
  2335. if result, err := e.executeSelect(sub); err == nil {
  2336. e.subqueryCache[sub] = result
  2337. }
  2338. }
  2339. var walk func(parser.Expr)
  2340. walk = func(x parser.Expr) {
  2341. if x == nil {
  2342. return
  2343. }
  2344. switch n := x.(type) {
  2345. case *parser.InExpr:
  2346. prime(n.Subquery)
  2347. walk(n.Left)
  2348. for _, v := range n.Values {
  2349. walk(v)
  2350. }
  2351. case *parser.SubqueryExpr:
  2352. prime(n.Query)
  2353. case *parser.ExistsExpr:
  2354. prime(n.Subquery)
  2355. case *parser.BinaryExpr:
  2356. walk(n.Left)
  2357. walk(n.Right)
  2358. case *parser.UnaryExpr:
  2359. walk(n.Operand)
  2360. case *parser.BetweenExpr:
  2361. walk(n.Left)
  2362. walk(n.Low)
  2363. walk(n.High)
  2364. case *parser.LikeExpr:
  2365. walk(n.Left)
  2366. walk(n.Pattern)
  2367. walk(n.Escape)
  2368. case *parser.IsNullExpr:
  2369. walk(n.Left)
  2370. case *parser.CaseExpr:
  2371. walk(n.Operand)
  2372. for _, w := range n.Whens {
  2373. walk(w.Condition)
  2374. walk(w.Result)
  2375. }
  2376. walk(n.Else)
  2377. case *parser.FunctionCall:
  2378. for _, a := range n.Args {
  2379. walk(a)
  2380. }
  2381. case *parser.ParenExpr:
  2382. walk(n.Expr)
  2383. case *parser.CastExpr:
  2384. walk(n.Expr)
  2385. }
  2386. }
  2387. walk(expr)
  2388. }
  2389. // executeUpdate executes an UPDATE statement.
  2390. func (e *Executor) executeUpdate(stmt *parser.UpdateStmt) (*Result, error) {
  2391. tableName := stmt.Table.Name
  2392. schema, err := e.schema.GetSchema(tableName)
  2393. if err != nil {
  2394. return nil, err
  2395. }
  2396. // Build filter
  2397. var filter func(storage.Row) bool
  2398. if stmt.Where != nil {
  2399. filter = func(row storage.Row) bool {
  2400. val, err := e.evalExpr(stmt.Where, row)
  2401. if err != nil {
  2402. return false
  2403. }
  2404. return toBool(val)
  2405. }
  2406. }
  2407. // Use UpdateFunc to evaluate expressions per-row (supports self-referencing like balance = balance + 100)
  2408. updateFn := func(row storage.Row) (storage.Row, error) {
  2409. updates := make(storage.Row)
  2410. for _, assign := range stmt.Set {
  2411. val, err := e.evalExpr(assign.Value, row)
  2412. if err != nil {
  2413. return nil, err
  2414. }
  2415. updates[assign.Column] = val
  2416. }
  2417. return updates, nil
  2418. }
  2419. if stmt.Where != nil {
  2420. column, value, equality := e.extractIndexableCondition(stmt.Where)
  2421. updatesPrimaryKey := false
  2422. for _, assignment := range stmt.Set {
  2423. if strings.EqualFold(assignment.Column, schema.PrimaryKey) {
  2424. updatesPrimaryKey = true
  2425. break
  2426. }
  2427. }
  2428. if equality && strings.EqualFold(column, schema.PrimaryKey) && !updatesPrimaryKey {
  2429. _, updated, err := e.session.UpdateByPK(tableName, fmt.Sprintf("%v", value), updateFn)
  2430. if err != nil {
  2431. return nil, err
  2432. }
  2433. count := 0
  2434. if updated {
  2435. count = 1
  2436. }
  2437. result := NewResult("UPDATE")
  2438. result.SetRowCount(count)
  2439. e.recordChanges(int64(count))
  2440. return result, nil
  2441. }
  2442. }
  2443. // Pre-evaluate subqueries in the predicate and assignments before the
  2444. // scan-based update takes the session lock.
  2445. e.primeSubqueries(stmt.Where)
  2446. for _, assign := range stmt.Set {
  2447. e.primeSubqueries(assign.Value)
  2448. }
  2449. count := 0
  2450. err = e.runDMLAtomic(tableName, func() error {
  2451. n, err := e.session.UpdateFunc(tableName, updateFn, filter)
  2452. if err != nil {
  2453. return err
  2454. }
  2455. count = n
  2456. return nil
  2457. })
  2458. if err != nil {
  2459. return nil, err
  2460. }
  2461. result := NewResult("UPDATE")
  2462. result.SetRowCount(count)
  2463. e.recordChanges(int64(count))
  2464. return result, nil
  2465. }
  2466. // executeDelete executes a DELETE statement.
  2467. func (e *Executor) executeDelete(stmt *parser.DeleteStmt) (*Result, error) {
  2468. tableName := stmt.Table.Name
  2469. schema, err := e.schema.GetSchema(tableName)
  2470. if err != nil {
  2471. return nil, err
  2472. }
  2473. // Build filter
  2474. var filter func(storage.Row) bool
  2475. if stmt.Where != nil {
  2476. filter = func(row storage.Row) bool {
  2477. val, err := e.evalExpr(stmt.Where, row)
  2478. if err != nil {
  2479. return false
  2480. }
  2481. return toBool(val)
  2482. }
  2483. }
  2484. if stmt.Where != nil {
  2485. column, value, equality := e.extractIndexableCondition(stmt.Where)
  2486. if equality && strings.EqualFold(column, schema.PrimaryKey) {
  2487. _, deleted, err := e.session.DeleteByPK(tableName, fmt.Sprintf("%v", value))
  2488. if err != nil {
  2489. return nil, err
  2490. }
  2491. count := 0
  2492. if deleted {
  2493. count = 1
  2494. }
  2495. result := NewResult("DELETE")
  2496. result.SetRowCount(count)
  2497. e.recordChanges(int64(count))
  2498. return result, nil
  2499. }
  2500. }
  2501. // Pre-evaluate subqueries in the predicate before the scan-based delete
  2502. // takes the session lock.
  2503. e.primeSubqueries(stmt.Where)
  2504. count, err := e.session.Delete(tableName, filter)
  2505. if err != nil {
  2506. return nil, err
  2507. }
  2508. result := NewResult("DELETE")
  2509. result.SetRowCount(count)
  2510. e.recordChanges(int64(count))
  2511. return result, nil
  2512. }
  2513. // executeCreateTable executes a CREATE TABLE statement.
  2514. func (e *Executor) executeCreateTable(stmt *parser.CreateTableStmt) (*Result, error) {
  2515. // Check if exists
  2516. if e.schema.TableExists(stmt.Table.Name) {
  2517. if stmt.IfNotExists {
  2518. result := NewResult("CREATE TABLE")
  2519. return result, nil
  2520. }
  2521. return nil, fmt.Errorf("table already exists: %s", stmt.Table.Name)
  2522. }
  2523. // Build schema
  2524. schema := &storage.Schema{
  2525. Name: stmt.Table.Name,
  2526. }
  2527. for _, colDef := range stmt.Columns {
  2528. col := storage.Column{
  2529. Name: colDef.Name,
  2530. Type: colDef.Type.Name,
  2531. Nullable: true,
  2532. }
  2533. for _, constraint := range colDef.Constraints {
  2534. switch constraint.Type {
  2535. case parser.ConstraintPrimaryKey:
  2536. col.PrimaryKey = true
  2537. col.Nullable = false
  2538. schema.PrimaryKey = col.Name
  2539. case parser.ConstraintNotNull:
  2540. col.Nullable = false
  2541. case parser.ConstraintDefault:
  2542. if constraint.Default != nil {
  2543. val, _ := e.evalExpr(constraint.Default, nil)
  2544. col.Default = val
  2545. }
  2546. case parser.ConstraintAutoIncrement:
  2547. schema.AutoIncrement = true
  2548. }
  2549. }
  2550. schema.Columns = append(schema.Columns, col)
  2551. }
  2552. // Handle table-level constraints
  2553. for _, constraint := range stmt.Constraints {
  2554. if constraint.Type == parser.ConstraintPrimaryKey && len(constraint.Columns) > 0 {
  2555. schema.PrimaryKey = constraint.Columns[0]
  2556. for i := range schema.Columns {
  2557. if strings.EqualFold(schema.Columns[i].Name, schema.PrimaryKey) {
  2558. schema.Columns[i].PrimaryKey = true
  2559. schema.Columns[i].Nullable = false
  2560. }
  2561. }
  2562. }
  2563. }
  2564. // Translate inline/table UNIQUE constraints (Gogs/GORM style) into the same
  2565. // scan-validated unique Index metadata that explicit CREATE UNIQUE INDEX
  2566. // produces, so both enforcement and the catalog observe them.
  2567. uniqIndexes := e.uniqueConstraintIndexes(stmt)
  2568. if err := e.schema.CreateTable(schema); err != nil {
  2569. if stmt.IfNotExists && strings.Contains(err.Error(), "table already exists") {
  2570. return NewResult("CREATE TABLE"), nil
  2571. }
  2572. return nil, err
  2573. }
  2574. // Register each materialized unique index. On failure, best-effort cleanup of
  2575. // the table and any indexes already created for it (DDL is not transactional).
  2576. var created []*storage.Index
  2577. for _, idx := range uniqIndexes {
  2578. if err := e.schema.CreateIndex(idx); err != nil {
  2579. for _, c := range created {
  2580. e.schema.DropIndex(c.Name)
  2581. }
  2582. e.schema.DropTable(stmt.Table.Name)
  2583. return nil, err
  2584. }
  2585. created = append(created, idx)
  2586. }
  2587. if err := e.SyncCatalog(); err != nil {
  2588. return nil, err
  2589. }
  2590. result := NewResult("CREATE TABLE")
  2591. return result, nil
  2592. }
  2593. // uniqueConstraintIndexes translates a CREATE TABLE's inline/table UNIQUE
  2594. // constraints into unique Index definitions. Named constraints keep their name;
  2595. // unnamed constraints (column-level UNIQUE, or bare UNIQUE(col,...)) receive a
  2596. // deterministic internal name derived from the table and columns.
  2597. func (e *Executor) uniqueConstraintIndexes(stmt *parser.CreateTableStmt) []*storage.Index {
  2598. var indexes []*storage.Index
  2599. used := make(map[string]bool)
  2600. uniqueName := func(base string, columns []string) string {
  2601. if base == "" {
  2602. base = "uniq_" + strings.ToLower(stmt.Table.Name) + "_" + strings.ToLower(strings.Join(columns, "_"))
  2603. }
  2604. name := base
  2605. for n := 2; used[strings.ToLower(name)]; n++ {
  2606. name = fmt.Sprintf("%s_%d", base, n)
  2607. }
  2608. used[strings.ToLower(name)] = true
  2609. return name
  2610. }
  2611. add := func(name string, columns []string) {
  2612. idx := &storage.Index{Name: uniqueName(name, columns), Table: stmt.Table.Name, Unique: true}
  2613. for _, c := range columns {
  2614. idx.Columns = append(idx.Columns, storage.IndexColumn{Name: c})
  2615. }
  2616. indexes = append(indexes, idx)
  2617. }
  2618. for _, constraint := range stmt.Constraints {
  2619. if constraint.Type == parser.ConstraintUnique && len(constraint.Columns) > 0 {
  2620. add(constraint.Name, constraint.Columns)
  2621. }
  2622. }
  2623. for _, colDef := range stmt.Columns {
  2624. for _, constraint := range colDef.Constraints {
  2625. if constraint.Type == parser.ConstraintUnique {
  2626. add("", []string{colDef.Name})
  2627. }
  2628. }
  2629. }
  2630. return indexes
  2631. }
  2632. // executeDropTable executes a DROP TABLE statement.
  2633. func (e *Executor) executeDropTable(stmt *parser.DropTableStmt) (*Result, error) {
  2634. for _, tableRef := range stmt.Tables {
  2635. if !e.schema.TableExists(tableRef.Name) {
  2636. if stmt.IfExists {
  2637. continue
  2638. }
  2639. return nil, fmt.Errorf("table not found: %s", tableRef.Name)
  2640. }
  2641. // First, drop all indexes associated with this table
  2642. indexes, _ := e.schema.ListTableIndexes(tableRef.Name)
  2643. for _, idx := range indexes {
  2644. // Clear index entries
  2645. columns := make([]string, len(idx.Columns))
  2646. for i, col := range idx.Columns {
  2647. columns[i] = col.Name
  2648. }
  2649. e.session.ClearIndex(idx.Name, tableRef.Name, columns)
  2650. // Drop the index schema
  2651. e.schema.DropIndex(idx.Name)
  2652. }
  2653. // DropTable removes durable rows and schema state together.
  2654. if err := e.schema.DropTable(tableRef.Name); err != nil {
  2655. return nil, err
  2656. }
  2657. e.session.InvalidateCache(tableRef.Name)
  2658. }
  2659. if err := e.SyncCatalog(); err != nil {
  2660. return nil, err
  2661. }
  2662. result := NewResult("DROP TABLE")
  2663. return result, nil
  2664. }
  2665. // executeCreateIndex creates a new index.
  2666. func (e *Executor) executeCreateIndex(stmt *parser.CreateIndexStmt) (*Result, error) {
  2667. // Check if index already exists
  2668. if e.schema.IndexExists(stmt.Name) {
  2669. if stmt.IfNotExists {
  2670. result := NewResult("CREATE INDEX")
  2671. return result, nil
  2672. }
  2673. return nil, fmt.Errorf("index already exists: %s", stmt.Name)
  2674. }
  2675. // Verify table exists
  2676. if !e.schema.TableExists(stmt.Table) {
  2677. return nil, fmt.Errorf("table not found: %s", stmt.Table)
  2678. }
  2679. // Verify columns exist
  2680. schema, err := e.schema.GetSchema(stmt.Table)
  2681. if err != nil {
  2682. return nil, err
  2683. }
  2684. for _, col := range stmt.Columns {
  2685. if _, found := schema.GetColumn(col.Name); !found {
  2686. return nil, fmt.Errorf("column not found: %s", col.Name)
  2687. }
  2688. }
  2689. // Create storage index
  2690. index := &storage.Index{
  2691. Name: stmt.Name,
  2692. Table: stmt.Table,
  2693. Unique: stmt.Unique,
  2694. }
  2695. for _, col := range stmt.Columns {
  2696. index.Columns = append(index.Columns, storage.IndexColumn{
  2697. Name: col.Name,
  2698. Desc: col.Desc,
  2699. })
  2700. }
  2701. if stmt.Unique {
  2702. // Validate existing rows and register the index under the table's
  2703. // exclusive gate so no concurrent writer can insert a conflicting value
  2704. // between validation and registration.
  2705. if err := e.table.CreateUniqueIndex(index); err != nil {
  2706. if stmt.IfNotExists && strings.Contains(err.Error(), "index already exists") {
  2707. return NewResult("CREATE INDEX"), nil
  2708. }
  2709. return nil, err
  2710. }
  2711. } else {
  2712. if err := e.schema.CreateIndex(index); err != nil {
  2713. if stmt.IfNotExists && strings.Contains(err.Error(), "index already exists") {
  2714. return NewResult("CREATE INDEX"), nil
  2715. }
  2716. return nil, err
  2717. }
  2718. }
  2719. // Build index entries for existing rows
  2720. columns := make([]string, len(stmt.Columns))
  2721. for i, col := range stmt.Columns {
  2722. columns[i] = col.Name
  2723. }
  2724. if err := e.session.BuildIndex(stmt.Name, stmt.Table, columns); err != nil {
  2725. // Rollback index creation on failure
  2726. e.schema.DropIndex(stmt.Name)
  2727. return nil, fmt.Errorf("failed to build index: %w", err)
  2728. }
  2729. result := NewResult("CREATE INDEX")
  2730. return result, nil
  2731. }
  2732. // executeDropIndex drops an index.
  2733. func (e *Executor) executeDropIndex(stmt *parser.DropIndexStmt) (*Result, error) {
  2734. if !e.schema.IndexExists(stmt.Name) {
  2735. if stmt.IfExists {
  2736. result := NewResult("DROP INDEX")
  2737. return result, nil
  2738. }
  2739. return nil, fmt.Errorf("index not found: %s", stmt.Name)
  2740. }
  2741. // Get index info to clear entries
  2742. index, err := e.schema.GetIndex(stmt.Name)
  2743. if err == nil && index != nil {
  2744. columns := make([]string, len(index.Columns))
  2745. for i, col := range index.Columns {
  2746. columns[i] = col.Name
  2747. }
  2748. e.session.ClearIndex(stmt.Name, index.Table, columns)
  2749. }
  2750. if err := e.schema.DropIndex(stmt.Name); err != nil {
  2751. return nil, err
  2752. }
  2753. result := NewResult("DROP INDEX")
  2754. return result, nil
  2755. }
  2756. func (e *Executor) executeCreateView(stmt *parser.CreateViewStmt) (*Result, error) {
  2757. name := strings.ToLower(stmt.View.Name)
  2758. if _, exists := e.views[name]; exists {
  2759. if stmt.IfNotExists {
  2760. return NewResult("CREATE VIEW"), nil
  2761. }
  2762. return nil, fmt.Errorf("view already exists: %s", stmt.View.Name)
  2763. }
  2764. e.views[name] = stmt.Select
  2765. // Derive view columns from SELECT list for catalog registration.
  2766. var viewCols []analyzer.ColumnInfo
  2767. hasStar := false
  2768. for _, col := range stmt.Select.Columns {
  2769. if col.Star {
  2770. hasStar = true
  2771. break
  2772. }
  2773. colName := col.Alias
  2774. if colName == "" {
  2775. if ref, ok := col.Expr.(*parser.ColumnRef); ok {
  2776. colName = ref.Column
  2777. } else {
  2778. colName = fmt.Sprintf("col_%d", len(viewCols))
  2779. }
  2780. }
  2781. viewCols = append(viewCols, analyzer.ColumnInfo{
  2782. Name: colName,
  2783. TableName: stmt.View.Name,
  2784. Type: analyzer.TypeAny,
  2785. Nullable: true,
  2786. })
  2787. }
  2788. // For SELECT *, pull columns from the underlying table(s).
  2789. if hasStar && len(stmt.Select.From) > 0 {
  2790. baseName := stmt.Select.From[0].Name
  2791. if schema, err := e.schema.GetSchema(baseName); err == nil {
  2792. for _, c := range schema.Columns {
  2793. viewCols = append(viewCols, analyzer.ColumnInfo{
  2794. Name: c.Name,
  2795. TableName: stmt.View.Name,
  2796. Type: analyzer.TypeAny,
  2797. Nullable: true,
  2798. })
  2799. }
  2800. }
  2801. }
  2802. // Register in catalog so the analyzer accepts SELECT FROM this view.
  2803. e.catalog.CreateTable(&analyzer.TableInfo{ //nolint:errcheck
  2804. Name: stmt.View.Name,
  2805. Columns: viewCols,
  2806. IsView: true,
  2807. })
  2808. return NewResult("CREATE VIEW"), nil
  2809. }
  2810. func (e *Executor) executeDropView(stmt *parser.DropViewStmt) (*Result, error) {
  2811. for _, ref := range stmt.Views {
  2812. name := strings.ToLower(ref.Name)
  2813. if _, exists := e.views[name]; !exists {
  2814. if stmt.IfExists {
  2815. continue
  2816. }
  2817. return nil, fmt.Errorf("view not found: %s", ref.Name)
  2818. }
  2819. delete(e.views, name)
  2820. e.catalog.DropTable(ref.Name) //nolint:errcheck
  2821. }
  2822. return NewResult("DROP VIEW"), nil
  2823. }
  2824. // executeAlterTable executes an ALTER TABLE statement.
  2825. func (e *Executor) executeAlterTable(stmt *parser.AlterTableStmt) (*Result, error) {
  2826. switch action := stmt.Action.(type) {
  2827. case *parser.AddColumnAction:
  2828. return e.executeAlterTableAddColumn(stmt.Table, action)
  2829. case *parser.DropColumnAction:
  2830. return e.executeAlterTableDropColumn(stmt.Table, action)
  2831. case *parser.RenameTableAction:
  2832. return e.executeAlterTableRename(stmt.Table, action)
  2833. case *parser.RenameColumnAction:
  2834. return e.executeAlterTableRenameColumn(stmt.Table, action)
  2835. default:
  2836. return nil, fmt.Errorf("unsupported ALTER TABLE action: %T", action)
  2837. }
  2838. }
  2839. // executeAlterTableAddColumn adds a column to a table.
  2840. func (e *Executor) executeAlterTableAddColumn(table string, action *parser.AddColumnAction) (*Result, error) {
  2841. if action.IfNotExists {
  2842. schema, err := e.schema.GetSchema(table)
  2843. if err != nil {
  2844. return nil, err
  2845. }
  2846. if _, exists := schema.GetColumn(action.Column.Name); exists {
  2847. return NewResult("ALTER TABLE"), nil
  2848. }
  2849. }
  2850. col := storage.Column{
  2851. Name: action.Column.Name,
  2852. Type: action.Column.Type.Name,
  2853. Nullable: true,
  2854. }
  2855. // Process column constraints
  2856. for _, constraint := range action.Column.Constraints {
  2857. switch constraint.Type {
  2858. case parser.ConstraintPrimaryKey:
  2859. col.PrimaryKey = true
  2860. col.Nullable = false
  2861. case parser.ConstraintNotNull:
  2862. col.Nullable = false
  2863. case parser.ConstraintDefault:
  2864. if constraint.Default != nil {
  2865. val, _ := e.evalExpr(constraint.Default, nil)
  2866. col.Default = val
  2867. }
  2868. }
  2869. }
  2870. if err := e.schema.AddColumn(table, col); err != nil {
  2871. if action.IfNotExists && strings.Contains(err.Error(), "column already exists") {
  2872. return NewResult("ALTER TABLE"), nil
  2873. }
  2874. return nil, err
  2875. }
  2876. // Update catalog
  2877. e.SyncCatalog()
  2878. result := NewResult("ALTER TABLE")
  2879. return result, nil
  2880. }
  2881. // executeAlterTableDropColumn drops a column from a table.
  2882. func (e *Executor) executeAlterTableDropColumn(table string, action *parser.DropColumnAction) (*Result, error) {
  2883. if err := e.schema.DropColumn(table, action.Column); err != nil {
  2884. return nil, err
  2885. }
  2886. // Update catalog
  2887. e.SyncCatalog()
  2888. result := NewResult("ALTER TABLE")
  2889. return result, nil
  2890. }
  2891. // executeAlterTableRename renames a table.
  2892. func (e *Executor) executeAlterTableRename(table string, action *parser.RenameTableAction) (*Result, error) {
  2893. if err := e.schema.RenameTable(table, action.NewName); err != nil {
  2894. return nil, err
  2895. }
  2896. e.session.InvalidateCache(table)
  2897. e.session.InvalidateCache(action.NewName)
  2898. // Update catalog
  2899. e.SyncCatalog()
  2900. result := NewResult("ALTER TABLE")
  2901. return result, nil
  2902. }
  2903. // executeAlterTableRenameColumn renames a column.
  2904. func (e *Executor) executeAlterTableRenameColumn(table string, action *parser.RenameColumnAction) (*Result, error) {
  2905. if err := e.schema.RenameColumn(table, action.OldName, action.NewName); err != nil {
  2906. return nil, err
  2907. }
  2908. // Update catalog
  2909. e.SyncCatalog()
  2910. result := NewResult("ALTER TABLE")
  2911. return result, nil
  2912. }
  2913. // Transaction execution methods
  2914. // executeBegin starts a new transaction.
  2915. func (e *Executor) executeBegin(stmt *parser.BeginStmt) (*Result, error) {
  2916. if e.inTransaction {
  2917. return nil, fmt.Errorf("cannot start a transaction within a transaction")
  2918. }
  2919. if err := e.session.Begin(); err != nil {
  2920. return nil, err
  2921. }
  2922. e.inTransaction = true
  2923. e.savepoints = nil
  2924. e.savepointPositions = nil
  2925. result := NewResult("BEGIN")
  2926. return result, nil
  2927. }
  2928. // executeCommit commits the current transaction.
  2929. func (e *Executor) executeCommit(stmt *parser.CommitStmt) (*Result, error) {
  2930. if !e.inTransaction {
  2931. return nil, fmt.Errorf("cannot commit: no transaction in progress")
  2932. }
  2933. if err := e.session.Commit(); err != nil {
  2934. e.inTransaction = false
  2935. e.savepoints = nil
  2936. e.savepointPositions = nil
  2937. return nil, err
  2938. }
  2939. e.inTransaction = false
  2940. e.savepoints = nil
  2941. e.savepointPositions = nil
  2942. result := NewResult("COMMIT")
  2943. return result, nil
  2944. }
  2945. // executeRollback rolls back the current transaction or to a savepoint.
  2946. func (e *Executor) executeRollback(stmt *parser.RollbackStmt) (*Result, error) {
  2947. if !e.inTransaction {
  2948. return nil, fmt.Errorf("cannot rollback: no transaction in progress")
  2949. }
  2950. if stmt.Savepoint != "" {
  2951. // Rollback to savepoint
  2952. return e.rollbackToSavepoint(stmt.Savepoint)
  2953. }
  2954. if err := e.session.Rollback(); err != nil {
  2955. return nil, err
  2956. }
  2957. e.inTransaction = false
  2958. e.savepoints = nil
  2959. e.savepointPositions = nil
  2960. // total_changes() is monotonic (SQLite semantics): it is NOT decremented on
  2961. // rollback. last_insert_rowid() and changes() also intentionally hold.
  2962. result := NewResult("ROLLBACK")
  2963. return result, nil
  2964. }
  2965. // executeSavepoint creates a savepoint.
  2966. func (e *Executor) executeSavepoint(stmt *parser.SavepointStmt) (*Result, error) {
  2967. if !e.inTransaction {
  2968. // SQLite allows SAVEPOINT outside transaction (starts implicit transaction)
  2969. if err := e.session.Begin(); err != nil {
  2970. return nil, err
  2971. }
  2972. e.inTransaction = true
  2973. e.savepoints = nil
  2974. e.savepointPositions = nil
  2975. }
  2976. // Add savepoint marker
  2977. e.savepoints = append(e.savepoints, stmt.Name)
  2978. e.savepointPositions = append(e.savepointPositions, e.session.Snapshot())
  2979. result := NewResult("SAVEPOINT")
  2980. return result, nil
  2981. }
  2982. // executeRelease releases a savepoint.
  2983. func (e *Executor) executeRelease(stmt *parser.ReleaseStmt) (*Result, error) {
  2984. if !e.inTransaction {
  2985. return nil, fmt.Errorf("cannot release savepoint: no transaction in progress")
  2986. }
  2987. // Find and remove the savepoint
  2988. found := false
  2989. for i := len(e.savepoints) - 1; i >= 0; i-- {
  2990. if e.savepoints[i] == stmt.Name {
  2991. e.savepoints = e.savepoints[:i]
  2992. e.savepointPositions = e.savepointPositions[:i]
  2993. found = true
  2994. break
  2995. }
  2996. }
  2997. if !found {
  2998. return nil, fmt.Errorf("no such savepoint: %s", stmt.Name)
  2999. }
  3000. result := NewResult("RELEASE")
  3001. return result, nil
  3002. }
  3003. // executeAttach attaches a database.
  3004. func (e *Executor) executeAttach(stmt *parser.AttachStmt) (*Result, error) {
  3005. // Check if alias already exists
  3006. if _, exists := e.attachedDatabases[stmt.Alias]; exists {
  3007. return nil, fmt.Errorf("database alias already exists: %s", stmt.Alias)
  3008. }
  3009. // Reserved alias check
  3010. if strings.EqualFold(stmt.Alias, "temp") || strings.EqualFold(stmt.Alias, "temporary") {
  3011. return nil, fmt.Errorf("reserved database alias: %s", stmt.Alias)
  3012. }
  3013. // Get the pool from the main schema manager
  3014. pool := e.schema.GetPool()
  3015. // Create new schema and table managers for the attached database
  3016. // In PizzaKV, each database is just a different namespace/prefix
  3017. schema := storage.NewSchemaManager(pool, stmt.FilePath)
  3018. table := storage.NewTableManager(pool, schema, stmt.FilePath)
  3019. // Register the database connection
  3020. e.attachedDatabases[stmt.Alias] = &DatabaseConnection{
  3021. Alias: stmt.Alias,
  3022. Path: stmt.FilePath,
  3023. Schema: schema,
  3024. Table: table,
  3025. }
  3026. // Sync the catalog with the attached database's tables
  3027. tables, _ := schema.ListTables()
  3028. for _, tableName := range tables {
  3029. tSchema, err := schema.GetSchema(tableName)
  3030. if err != nil {
  3031. continue
  3032. }
  3033. // Add with database prefix
  3034. tableInfo := tSchema.ToAnalyzerTableInfo()
  3035. tableInfo.Name = stmt.Alias + "." + tableInfo.Name
  3036. e.catalog.CreateTable(tableInfo)
  3037. }
  3038. result := NewResult("ATTACH")
  3039. return result, nil
  3040. }
  3041. // executeDetach detaches a database.
  3042. func (e *Executor) executeDetach(stmt *parser.DetachStmt) (*Result, error) {
  3043. // Cannot detach main database
  3044. if strings.EqualFold(stmt.Alias, "main") {
  3045. return nil, fmt.Errorf("cannot detach main database")
  3046. }
  3047. // Check if database exists
  3048. if _, exists := e.attachedDatabases[stmt.Alias]; !exists {
  3049. return nil, fmt.Errorf("no such database: %s", stmt.Alias)
  3050. }
  3051. // Remove from attached databases
  3052. delete(e.attachedDatabases, stmt.Alias)
  3053. // Note: We don't remove from catalog as that would be more complex
  3054. // In a production system, we'd need to track which tables belong to which database
  3055. result := NewResult("DETACH")
  3056. return result, nil
  3057. }
  3058. // rollbackToSavepoint rolls back to a specific savepoint.
  3059. func (e *Executor) rollbackToSavepoint(name string) (*Result, error) {
  3060. // Find savepoint index
  3061. savepointIdx := -1
  3062. for i := len(e.savepoints) - 1; i >= 0; i-- {
  3063. if e.savepoints[i] == name {
  3064. savepointIdx = i
  3065. break
  3066. }
  3067. }
  3068. if savepointIdx == -1 {
  3069. return nil, fmt.Errorf("no such savepoint: %s", name)
  3070. }
  3071. logPosition := e.savepointPositions[savepointIdx]
  3072. e.session.RollbackTo(logPosition)
  3073. // Remove savepoints after the target
  3074. e.savepoints = e.savepoints[:savepointIdx+1]
  3075. e.savepointPositions = e.savepointPositions[:savepointIdx+1]
  3076. result := NewResult("ROLLBACK")
  3077. return result, nil
  3078. }
  3079. // RollbackActive rolls back an open transaction, such as when its client
  3080. // disconnects before sending COMMIT or ROLLBACK.
  3081. func (e *Executor) RollbackActive() error {
  3082. if !e.inTransaction {
  3083. return nil
  3084. }
  3085. _, err := e.executeRollback(&parser.RollbackStmt{})
  3086. return err
  3087. }
  3088. // extractIndexableCondition extracts column name and value from a simple equality condition.
  3089. // Returns (column, value, true) if the expression is column = literal.
  3090. func (e *Executor) extractIndexableCondition(expr parser.Expr) (string, interface{}, bool) {
  3091. binExpr, ok := expr.(*parser.BinaryExpr)
  3092. if !ok {
  3093. return "", nil, false
  3094. }
  3095. // Only handle equality for now
  3096. if binExpr.Op != lexer.TokenEq {
  3097. return "", nil, false
  3098. }
  3099. // Check for column = literal pattern
  3100. colRef, leftIsCol := binExpr.Left.(*parser.ColumnRef)
  3101. litExpr, rightIsLit := binExpr.Right.(*parser.LiteralExpr)
  3102. if leftIsCol && rightIsLit {
  3103. val, _ := e.evalLiteral(litExpr)
  3104. return colRef.Column, val, true
  3105. }
  3106. // Check for literal = column pattern
  3107. litExpr, leftIsLit := binExpr.Left.(*parser.LiteralExpr)
  3108. colRef, rightIsCol := binExpr.Right.(*parser.ColumnRef)
  3109. if leftIsLit && rightIsCol {
  3110. val, _ := e.evalLiteral(litExpr)
  3111. return colRef.Column, val, true
  3112. }
  3113. return "", nil, false
  3114. }
  3115. // executePragma executes a PRAGMA statement.
  3116. func (e *Executor) executePragma(stmt *parser.PragmaStmt) (*Result, error) {
  3117. switch stmt.Name {
  3118. case "table_info":
  3119. return e.pragmaTableInfo(stmt.Arg)
  3120. case "table_list":
  3121. return e.pragmaTableList()
  3122. case "database_list":
  3123. return e.pragmaDatabaseList()
  3124. case "version":
  3125. return e.pragmaVersion()
  3126. default:
  3127. return nil, fmt.Errorf("unknown pragma: %s", stmt.Name)
  3128. }
  3129. }
  3130. // pragmaTableInfo returns column information for a table.
  3131. func (e *Executor) pragmaTableInfo(tableName string) (*Result, error) {
  3132. if tableName == "" {
  3133. return nil, fmt.Errorf("table_info requires a table name")
  3134. }
  3135. schema, err := e.schema.GetSchema(tableName)
  3136. if err != nil {
  3137. return nil, err
  3138. }
  3139. result := NewResult("PRAGMA")
  3140. result.AddColumn("cid")
  3141. result.AddColumn("name")
  3142. result.AddColumn("type")
  3143. result.AddColumn("notnull")
  3144. result.AddColumn("dflt_value")
  3145. result.AddColumn("pk")
  3146. for i, col := range schema.Columns {
  3147. notnull := 0
  3148. if !col.Nullable {
  3149. notnull = 1
  3150. }
  3151. pk := 0
  3152. if col.PrimaryKey {
  3153. pk = 1
  3154. }
  3155. result.AddRow(int64(i), col.Name, col.Type, int64(notnull), col.Default, int64(pk))
  3156. }
  3157. return result, nil
  3158. }
  3159. // pragmaTableList returns a list of all tables.
  3160. func (e *Executor) pragmaTableList() (*Result, error) {
  3161. tables, err := e.schema.ListTables()
  3162. if err != nil {
  3163. return nil, err
  3164. }
  3165. result := NewResult("PRAGMA")
  3166. result.AddColumn("schema")
  3167. result.AddColumn("name")
  3168. result.AddColumn("type")
  3169. for _, t := range tables {
  3170. result.AddRow("main", t, "table")
  3171. }
  3172. return result, nil
  3173. }
  3174. // pragmaDatabaseList returns a list of databases.
  3175. func (e *Executor) pragmaDatabaseList() (*Result, error) {
  3176. result := NewResult("PRAGMA")
  3177. result.AddColumn("seq")
  3178. result.AddColumn("name")
  3179. result.AddColumn("file")
  3180. // We only have one database
  3181. result.AddRow(int64(0), "main", "")
  3182. return result, nil
  3183. }
  3184. // pragmaVersion returns the PizzaSQL version.
  3185. func (e *Executor) pragmaVersion() (*Result, error) {
  3186. result := NewResult("PRAGMA")
  3187. result.AddColumn("version")
  3188. result.AddRow(version.String())
  3189. return result, nil
  3190. }
  3191. // executeExplain executes an EXPLAIN statement.
  3192. func (e *Executor) executeExplain(stmt *parser.ExplainStmt) (*Result, error) {
  3193. result := NewResult("EXPLAIN")
  3194. if stmt.QueryPlan {
  3195. // EXPLAIN QUERY PLAN format
  3196. result.AddColumn("id")
  3197. result.AddColumn("parent")
  3198. result.AddColumn("notused")
  3199. result.AddColumn("detail")
  3200. plan := e.generateQueryPlan(stmt.Statement)
  3201. for i, step := range plan {
  3202. result.AddRow(int64(i), int64(0), int64(0), step)
  3203. }
  3204. } else {
  3205. // Simple EXPLAIN format
  3206. result.AddColumn("addr")
  3207. result.AddColumn("opcode")
  3208. result.AddColumn("p1")
  3209. result.AddColumn("p2")
  3210. result.AddColumn("p3")
  3211. result.AddColumn("p4")
  3212. result.AddColumn("p5")
  3213. result.AddColumn("comment")
  3214. ops := e.generateOpcodes(stmt.Statement)
  3215. for i, op := range ops {
  3216. result.AddRow(int64(i), op, int64(0), int64(0), int64(0), "", int64(0), "")
  3217. }
  3218. }
  3219. return result, nil
  3220. }
  3221. // generateQueryPlan generates a simple query plan description.
  3222. func (e *Executor) generateQueryPlan(stmt parser.Statement) []string {
  3223. var plan []string
  3224. switch s := stmt.(type) {
  3225. case *parser.SelectStmt:
  3226. if len(s.From) > 0 {
  3227. plan = append(plan, fmt.Sprintf("SCAN TABLE %s", s.From[0].Name))
  3228. if s.Where != nil {
  3229. plan = append(plan, "FILTER")
  3230. }
  3231. if len(s.OrderBy) > 0 {
  3232. plan = append(plan, "SORT")
  3233. }
  3234. if s.Limit != nil {
  3235. plan = append(plan, "LIMIT")
  3236. }
  3237. } else {
  3238. plan = append(plan, "SCALAR EXPRESSION")
  3239. }
  3240. case *parser.InsertStmt:
  3241. plan = append(plan, fmt.Sprintf("INSERT INTO %s", s.Table.Name))
  3242. case *parser.UpdateStmt:
  3243. plan = append(plan, fmt.Sprintf("SCAN TABLE %s", s.Table.Name))
  3244. plan = append(plan, "UPDATE")
  3245. case *parser.DeleteStmt:
  3246. plan = append(plan, fmt.Sprintf("SCAN TABLE %s", s.Table.Name))
  3247. plan = append(plan, "DELETE")
  3248. default:
  3249. plan = append(plan, "EXECUTE")
  3250. }
  3251. return plan
  3252. }
  3253. // generateOpcodes generates simplified opcodes for EXPLAIN.
  3254. func (e *Executor) generateOpcodes(stmt parser.Statement) []string {
  3255. var ops []string
  3256. switch s := stmt.(type) {
  3257. case *parser.SelectStmt:
  3258. ops = append(ops, "Init")
  3259. if len(s.From) > 0 {
  3260. ops = append(ops, "OpenRead")
  3261. ops = append(ops, "Rewind")
  3262. ops = append(ops, "Column")
  3263. ops = append(ops, "ResultRow")
  3264. ops = append(ops, "Next")
  3265. ops = append(ops, "Close")
  3266. } else {
  3267. ops = append(ops, "Integer")
  3268. ops = append(ops, "ResultRow")
  3269. }
  3270. ops = append(ops, "Halt")
  3271. case *parser.InsertStmt:
  3272. ops = append(ops, "Init")
  3273. ops = append(ops, "OpenWrite")
  3274. ops = append(ops, "NewRowid")
  3275. ops = append(ops, "Insert")
  3276. ops = append(ops, "Close")
  3277. ops = append(ops, "Halt")
  3278. case *parser.UpdateStmt:
  3279. ops = append(ops, "Init")
  3280. ops = append(ops, "OpenWrite")
  3281. ops = append(ops, "Rewind")
  3282. ops = append(ops, "Column")
  3283. ops = append(ops, "Update")
  3284. ops = append(ops, "Next")
  3285. ops = append(ops, "Close")
  3286. ops = append(ops, "Halt")
  3287. case *parser.DeleteStmt:
  3288. ops = append(ops, "Init")
  3289. ops = append(ops, "OpenWrite")
  3290. ops = append(ops, "Rewind")
  3291. ops = append(ops, "Delete")
  3292. ops = append(ops, "Next")
  3293. ops = append(ops, "Close")
  3294. ops = append(ops, "Halt")
  3295. default:
  3296. ops = append(ops, "Init")
  3297. ops = append(ops, "Halt")
  3298. }
  3299. return ops
  3300. }
  3301. // evalExpr evaluates an expression.
  3302. func (e *Executor) evalExpr(expr parser.Expr, row storage.Row) (interface{}, error) {
  3303. if expr == nil {
  3304. return nil, nil
  3305. }
  3306. switch ex := expr.(type) {
  3307. case *parser.LiteralExpr:
  3308. return e.evalLiteral(ex)
  3309. case *parser.ColumnRef:
  3310. return e.evalColumnRef(ex, row)
  3311. case *parser.BinaryExpr:
  3312. return e.evalBinaryExpr(ex, row)
  3313. case *parser.UnaryExpr:
  3314. return e.evalUnaryExpr(ex, row)
  3315. case *parser.FunctionCall:
  3316. return e.evalFunctionCall(ex, row)
  3317. case *parser.ParenExpr:
  3318. return e.evalExpr(ex.Expr, row)
  3319. case *parser.CaseExpr:
  3320. return e.evalCaseExpr(ex, row)
  3321. case *parser.InExpr:
  3322. return e.evalInExpr(ex, row)
  3323. case *parser.BetweenExpr:
  3324. return e.evalBetweenExpr(ex, row)
  3325. case *parser.LikeExpr:
  3326. return e.evalLikeExpr(ex, row)
  3327. case *parser.IsNullExpr:
  3328. return e.evalIsNullExpr(ex, row)
  3329. case *parser.CastExpr:
  3330. return e.evalCastExpr(ex, row)
  3331. case *parser.SubqueryExpr:
  3332. return e.evalSubqueryExpr(ex, row)
  3333. case *parser.ExistsExpr:
  3334. return e.evalExistsExpr(ex, row)
  3335. default:
  3336. return nil, fmt.Errorf("unsupported expression type: %T", expr)
  3337. }
  3338. }
  3339. func (e *Executor) evalLiteral(lit *parser.LiteralExpr) (interface{}, error) {
  3340. switch lit.Type {
  3341. case lexer.TokenNumber:
  3342. // Check for scientific notation (e.g., 1e+06) or decimal point
  3343. if strings.Contains(lit.Value, ".") || strings.ContainsAny(lit.Value, "eE") {
  3344. f, err := strconv.ParseFloat(lit.Value, 64)
  3345. if err != nil {
  3346. return nil, err
  3347. }
  3348. // If it's a whole number (no fractional part), return as int64
  3349. if f == float64(int64(f)) {
  3350. return int64(f), nil
  3351. }
  3352. return f, nil
  3353. }
  3354. return strconv.ParseInt(lit.Value, 10, 64)
  3355. case lexer.TokenString:
  3356. return lit.Value, nil
  3357. case lexer.TokenNULL:
  3358. return nil, nil
  3359. case lexer.TokenTRUE:
  3360. return true, nil
  3361. case lexer.TokenFALSE:
  3362. return false, nil
  3363. default:
  3364. return lit.Value, nil
  3365. }
  3366. }
  3367. func (e *Executor) evalColumnRef(ref *parser.ColumnRef, row storage.Row) (interface{}, error) {
  3368. if row == nil {
  3369. return nil, fmt.Errorf("no row context for column: %s", ref.Column)
  3370. }
  3371. // For qualified column references (table.column):
  3372. //
  3373. // Resolution order:
  3374. // 1. Exact qualified key in outer row ("t1.b" → outer)
  3375. // 2. Case-insensitive qualified in outer row
  3376. // 3. Exact qualified key in current row ("x.b" → inner alias)
  3377. // 4. Case-insensitive qualified in current row
  3378. // 5. Unqualified in outer row — only reached when qualified lookup in current
  3379. // row failed, meaning the qualifier refers to an outer table not the inner
  3380. // alias (e.g. "t1.b" in a subquery "FROM t1 AS x" resolves here).
  3381. // 6. Unqualified in current row (last resort)
  3382. if ref.Table != "" {
  3383. if e.outerRow != nil {
  3384. // Step 1-2: qualified lookup in outer row
  3385. if val, ok := e.outerRow[ref.Table+"."+ref.Column]; ok {
  3386. return val, nil
  3387. }
  3388. for k, v := range e.outerRow {
  3389. if strings.EqualFold(k, ref.Table+"."+ref.Column) {
  3390. return v, nil
  3391. }
  3392. }
  3393. }
  3394. // Step 3-4: qualified lookup in current row
  3395. if val, ok := row[ref.Table+"."+ref.Column]; ok {
  3396. return val, nil
  3397. }
  3398. for k, v := range row {
  3399. if strings.EqualFold(k, ref.Table+"."+ref.Column) {
  3400. return v, nil
  3401. }
  3402. }
  3403. // Step 5: qualified lookup failed in current row — try outer row unqualified.
  3404. // This handles correlated subqueries where the qualifier names an outer table
  3405. // (e.g. "t1.b" when the inner FROM is "t1 AS x", so current row has "x.b"
  3406. // but no "t1.b").
  3407. if e.outerRow != nil {
  3408. if val, ok := e.outerRow[ref.Column]; ok {
  3409. return val, nil
  3410. }
  3411. for k, v := range e.outerRow {
  3412. if strings.EqualFold(k, ref.Column) {
  3413. return v, nil
  3414. }
  3415. }
  3416. }
  3417. }
  3418. // Step 6: unqualified fallback in current row (handles unqualified refs and
  3419. // single-table queries like "SELECT t1.a FROM t1" where rows have plain keys).
  3420. if val, ok := row[ref.Column]; ok {
  3421. return val, nil
  3422. }
  3423. for k, v := range row {
  3424. if strings.EqualFold(k, ref.Column) {
  3425. return v, nil
  3426. }
  3427. }
  3428. // For unqualified refs with an outer row context (ref.Table == "").
  3429. if e.outerRow != nil && ref.Table == "" {
  3430. if val, ok := e.outerRow[ref.Column]; ok {
  3431. return val, nil
  3432. }
  3433. for k, v := range e.outerRow {
  3434. if strings.EqualFold(k, ref.Column) {
  3435. return v, nil
  3436. }
  3437. }
  3438. }
  3439. // Hidden rowid alias (rowid/oid/_rowid_): only used when the row carries no
  3440. // real column of that name. SQLite semantics give an explicit column named
  3441. // oid/rowid/_rowid_ precedence over the hidden rowid alias, so this fallback
  3442. // runs last.
  3443. if storage.IsRowIDColumn(ref.Column) {
  3444. if val, ok := row["_rowid_"]; ok {
  3445. return val, nil
  3446. }
  3447. }
  3448. return nil, nil // Column not found, return NULL
  3449. }
  3450. func (e *Executor) evalBinaryExpr(expr *parser.BinaryExpr, row storage.Row) (interface{}, error) {
  3451. left, err := e.evalExpr(expr.Left, row)
  3452. if err != nil {
  3453. return nil, err
  3454. }
  3455. right, err := e.evalExpr(expr.Right, row)
  3456. if err != nil {
  3457. return nil, err
  3458. }
  3459. switch expr.Op {
  3460. case lexer.TokenPlus:
  3461. if left == nil || right == nil {
  3462. return nil, nil
  3463. }
  3464. if isIntVal(left) && isIntVal(right) {
  3465. return toInt64(left) + toInt64(right), nil
  3466. }
  3467. return toFloat(left) + toFloat(right), nil
  3468. case lexer.TokenMinus:
  3469. if left == nil || right == nil {
  3470. return nil, nil
  3471. }
  3472. if isIntVal(left) && isIntVal(right) {
  3473. return toInt64(left) - toInt64(right), nil
  3474. }
  3475. return toFloat(left) - toFloat(right), nil
  3476. case lexer.TokenStar:
  3477. if left == nil || right == nil {
  3478. return nil, nil
  3479. }
  3480. if isIntVal(left) && isIntVal(right) {
  3481. return toInt64(left) * toInt64(right), nil
  3482. }
  3483. return toFloat(left) * toFloat(right), nil
  3484. case lexer.TokenSlash:
  3485. if left == nil || right == nil {
  3486. return nil, nil
  3487. }
  3488. // Integer division when both operands are integers (truncates toward zero, matching SQLite)
  3489. if isIntVal(left) && isIntVal(right) {
  3490. ri := toInt64(right)
  3491. if ri == 0 {
  3492. return nil, nil
  3493. }
  3494. return toInt64(left) / ri, nil
  3495. }
  3496. r := toFloat(right)
  3497. if r == 0 {
  3498. return nil, nil // Division by zero returns NULL
  3499. }
  3500. return toFloat(left) / r, nil
  3501. case lexer.TokenPercent:
  3502. if left == nil || right == nil {
  3503. return nil, nil
  3504. }
  3505. if isIntVal(left) && isIntVal(right) {
  3506. ri := toInt64(right)
  3507. if ri == 0 {
  3508. return nil, nil
  3509. }
  3510. return toInt64(left) % ri, nil
  3511. }
  3512. return int64(toFloat(left)) % int64(toFloat(right)), nil
  3513. case lexer.TokenEq:
  3514. if left == nil || right == nil {
  3515. return nil, nil
  3516. }
  3517. return compare(left, right) == 0, nil
  3518. case lexer.TokenNeq:
  3519. if left == nil || right == nil {
  3520. return nil, nil
  3521. }
  3522. return compare(left, right) != 0, nil
  3523. case lexer.TokenLt:
  3524. if left == nil || right == nil {
  3525. return nil, nil
  3526. }
  3527. return compare(left, right) < 0, nil
  3528. case lexer.TokenLte:
  3529. if left == nil || right == nil {
  3530. return nil, nil
  3531. }
  3532. return compare(left, right) <= 0, nil
  3533. case lexer.TokenGt:
  3534. if left == nil || right == nil {
  3535. return nil, nil
  3536. }
  3537. return compare(left, right) > 0, nil
  3538. case lexer.TokenGte:
  3539. if left == nil || right == nil {
  3540. return nil, nil
  3541. }
  3542. return compare(left, right) >= 0, nil
  3543. case lexer.TokenAND:
  3544. // Three-value logic: FALSE AND x = FALSE; NULL AND TRUE = NULL; TRUE AND TRUE = TRUE
  3545. if left != nil && !toBool(left) {
  3546. return false, nil
  3547. }
  3548. if right != nil && !toBool(right) {
  3549. return false, nil
  3550. }
  3551. if left == nil || right == nil {
  3552. return nil, nil
  3553. }
  3554. return true, nil
  3555. case lexer.TokenOR:
  3556. // Three-value logic: TRUE OR x = TRUE; NULL OR FALSE = NULL; FALSE OR FALSE = FALSE
  3557. if left != nil && toBool(left) {
  3558. return true, nil
  3559. }
  3560. if right != nil && toBool(right) {
  3561. return true, nil
  3562. }
  3563. if left == nil || right == nil {
  3564. return nil, nil
  3565. }
  3566. return false, nil
  3567. case lexer.TokenConcat:
  3568. return toString(left) + toString(right), nil
  3569. default:
  3570. return nil, fmt.Errorf("unsupported operator: %v", expr.Op)
  3571. }
  3572. }
  3573. // applyBinaryOp applies a binary operator to two already-evaluated values.
  3574. func (e *Executor) applyBinaryOp(op lexer.TokenType, left, right interface{}) (interface{}, error) {
  3575. dummy := &parser.BinaryExpr{Op: op}
  3576. _ = dummy
  3577. switch op {
  3578. case lexer.TokenPlus:
  3579. if left == nil || right == nil {
  3580. return nil, nil
  3581. }
  3582. if isIntVal(left) && isIntVal(right) {
  3583. return toInt64(left) + toInt64(right), nil
  3584. }
  3585. return toFloat(left) + toFloat(right), nil
  3586. case lexer.TokenMinus:
  3587. if left == nil || right == nil {
  3588. return nil, nil
  3589. }
  3590. if isIntVal(left) && isIntVal(right) {
  3591. return toInt64(left) - toInt64(right), nil
  3592. }
  3593. return toFloat(left) - toFloat(right), nil
  3594. case lexer.TokenStar:
  3595. if left == nil || right == nil {
  3596. return nil, nil
  3597. }
  3598. if isIntVal(left) && isIntVal(right) {
  3599. return toInt64(left) * toInt64(right), nil
  3600. }
  3601. return toFloat(left) * toFloat(right), nil
  3602. case lexer.TokenSlash:
  3603. if left == nil || right == nil {
  3604. return nil, nil
  3605. }
  3606. if isIntVal(left) && isIntVal(right) {
  3607. ri := toInt64(right)
  3608. if ri == 0 {
  3609. return nil, nil
  3610. }
  3611. return toInt64(left) / ri, nil
  3612. }
  3613. r := toFloat(right)
  3614. if r == 0 {
  3615. return nil, nil
  3616. }
  3617. return toFloat(left) / r, nil
  3618. case lexer.TokenPercent:
  3619. if left == nil || right == nil {
  3620. return nil, nil
  3621. }
  3622. if isIntVal(left) && isIntVal(right) {
  3623. ri := toInt64(right)
  3624. if ri == 0 {
  3625. return nil, nil
  3626. }
  3627. return toInt64(left) % ri, nil
  3628. }
  3629. return int64(toFloat(left)) % int64(toFloat(right)), nil
  3630. case lexer.TokenEq:
  3631. if left == nil || right == nil {
  3632. return nil, nil
  3633. }
  3634. return compare(left, right) == 0, nil
  3635. case lexer.TokenNeq:
  3636. if left == nil || right == nil {
  3637. return nil, nil
  3638. }
  3639. return compare(left, right) != 0, nil
  3640. case lexer.TokenLt:
  3641. if left == nil || right == nil {
  3642. return nil, nil
  3643. }
  3644. return compare(left, right) < 0, nil
  3645. case lexer.TokenLte:
  3646. if left == nil || right == nil {
  3647. return nil, nil
  3648. }
  3649. return compare(left, right) <= 0, nil
  3650. case lexer.TokenGt:
  3651. if left == nil || right == nil {
  3652. return nil, nil
  3653. }
  3654. return compare(left, right) > 0, nil
  3655. case lexer.TokenGte:
  3656. if left == nil || right == nil {
  3657. return nil, nil
  3658. }
  3659. return compare(left, right) >= 0, nil
  3660. case lexer.TokenAND:
  3661. if left != nil && !toBool(left) {
  3662. return false, nil
  3663. }
  3664. if right != nil && !toBool(right) {
  3665. return false, nil
  3666. }
  3667. if left == nil || right == nil {
  3668. return nil, nil
  3669. }
  3670. return true, nil
  3671. case lexer.TokenOR:
  3672. if left != nil && toBool(left) {
  3673. return true, nil
  3674. }
  3675. if right != nil && toBool(right) {
  3676. return true, nil
  3677. }
  3678. if left == nil || right == nil {
  3679. return nil, nil
  3680. }
  3681. return false, nil
  3682. case lexer.TokenConcat:
  3683. return toString(left) + toString(right), nil
  3684. default:
  3685. return nil, fmt.Errorf("unsupported operator: %v", op)
  3686. }
  3687. }
  3688. // evalBuiltinFunction applies a named scalar function to pre-evaluated args.
  3689. func (e *Executor) evalBuiltinFunction(name string, args []interface{}) (interface{}, error) {
  3690. switch name {
  3691. case "NULLIF":
  3692. if len(args) >= 2 && compare(args[0], args[1]) == 0 {
  3693. return nil, nil
  3694. }
  3695. if len(args) > 0 {
  3696. return args[0], nil
  3697. }
  3698. case "IFNULL", "NVL":
  3699. if len(args) >= 2 {
  3700. if args[0] == nil {
  3701. return args[1], nil
  3702. }
  3703. return args[0], nil
  3704. }
  3705. case "COALESCE":
  3706. for _, a := range args {
  3707. if a != nil {
  3708. return a, nil
  3709. }
  3710. }
  3711. return nil, nil
  3712. case "ABS":
  3713. if len(args) > 0 && args[0] != nil {
  3714. if isIntVal(args[0]) {
  3715. v := toInt64(args[0])
  3716. if v < 0 {
  3717. return -v, nil
  3718. }
  3719. return v, nil
  3720. }
  3721. v := toFloat(args[0])
  3722. if v < 0 {
  3723. return -v, nil
  3724. }
  3725. return v, nil
  3726. }
  3727. case "LENGTH":
  3728. if len(args) > 0 && args[0] != nil {
  3729. return int64(len(fmt.Sprintf("%v", args[0]))), nil
  3730. }
  3731. }
  3732. // Fall back: store pre-evaluated values in row and build column refs.
  3733. row := make(storage.Row, len(args))
  3734. fn := &parser.FunctionCall{Name: name}
  3735. for i, a := range args {
  3736. key := fmt.Sprintf("__arg%d__", i)
  3737. row[key] = a
  3738. fn.Args = append(fn.Args, &parser.ColumnRef{Column: key})
  3739. }
  3740. return e.evalFunctionCall(fn, row)
  3741. }
  3742. func (e *Executor) evalUnaryExpr(expr *parser.UnaryExpr, row storage.Row) (interface{}, error) {
  3743. val, err := e.evalExpr(expr.Operand, row)
  3744. if err != nil {
  3745. return nil, err
  3746. }
  3747. switch expr.Op {
  3748. case lexer.TokenMinus:
  3749. if val == nil {
  3750. return nil, nil
  3751. }
  3752. if isIntVal(val) {
  3753. return -toInt64(val), nil
  3754. }
  3755. return -toFloat(val), nil
  3756. case lexer.TokenPlus:
  3757. if val == nil {
  3758. return nil, nil
  3759. }
  3760. if isIntVal(val) {
  3761. return toInt64(val), nil
  3762. }
  3763. return toFloat(val), nil
  3764. case lexer.TokenNOT:
  3765. if val == nil {
  3766. return nil, nil // NOT NULL = NULL
  3767. }
  3768. return !toBool(val), nil
  3769. default:
  3770. return val, nil
  3771. }
  3772. }
  3773. func (e *Executor) evalFunctionCall(fn *parser.FunctionCall, row storage.Row) (interface{}, error) {
  3774. name := strings.ToUpper(fn.Name)
  3775. // Evaluate arguments
  3776. args := make([]interface{}, len(fn.Args))
  3777. for i, arg := range fn.Args {
  3778. val, err := e.evalExpr(arg, row)
  3779. if err != nil {
  3780. return nil, err
  3781. }
  3782. args[i] = val
  3783. }
  3784. switch name {
  3785. case "UPPER":
  3786. if len(args) > 0 {
  3787. if args[0] == nil {
  3788. return nil, nil // NULL propagation
  3789. }
  3790. return strings.ToUpper(toString(args[0])), nil
  3791. }
  3792. case "LOWER":
  3793. if len(args) > 0 {
  3794. if args[0] == nil {
  3795. return nil, nil // NULL propagation
  3796. }
  3797. return strings.ToLower(toString(args[0])), nil
  3798. }
  3799. case "LENGTH":
  3800. if len(args) > 0 {
  3801. if args[0] == nil {
  3802. return nil, nil // NULL propagation
  3803. }
  3804. return int64(len(toString(args[0]))), nil
  3805. }
  3806. case "ABS":
  3807. if len(args) > 0 {
  3808. if args[0] == nil {
  3809. return nil, nil
  3810. }
  3811. v := toFloat(args[0])
  3812. if v < 0 {
  3813. return -v, nil
  3814. }
  3815. return v, nil
  3816. }
  3817. case "COALESCE":
  3818. for _, arg := range args {
  3819. if arg != nil {
  3820. return arg, nil
  3821. }
  3822. }
  3823. return nil, nil
  3824. case "NULLIF":
  3825. if len(args) >= 2 && compare(args[0], args[1]) == 0 {
  3826. return nil, nil
  3827. }
  3828. if len(args) > 0 {
  3829. return args[0], nil
  3830. }
  3831. case "IFNULL":
  3832. if len(args) >= 2 {
  3833. if args[0] == nil {
  3834. return args[1], nil
  3835. }
  3836. return args[0], nil
  3837. }
  3838. case "TYPEOF":
  3839. if len(args) > 0 {
  3840. switch args[0].(type) {
  3841. case nil:
  3842. return "null", nil
  3843. case int64, int:
  3844. return "integer", nil
  3845. case float64:
  3846. return "real", nil
  3847. case string:
  3848. return "text", nil
  3849. case []byte:
  3850. return "blob", nil
  3851. default:
  3852. return "text", nil
  3853. }
  3854. }
  3855. case "SUBSTR", "SUBSTRING":
  3856. if len(args) >= 2 {
  3857. s := toString(args[0])
  3858. start := int(toFloat(args[1])) - 1 // SQL is 1-indexed
  3859. if start < 0 {
  3860. start = 0
  3861. }
  3862. if start >= len(s) {
  3863. return "", nil
  3864. }
  3865. if len(args) >= 3 {
  3866. length := int(toFloat(args[2]))
  3867. if start+length > len(s) {
  3868. length = len(s) - start
  3869. }
  3870. return s[start : start+length], nil
  3871. }
  3872. return s[start:], nil
  3873. }
  3874. case "TRIM":
  3875. if len(args) > 0 {
  3876. return strings.TrimSpace(toString(args[0])), nil
  3877. }
  3878. case "REPLACE":
  3879. if len(args) >= 3 {
  3880. return strings.ReplaceAll(toString(args[0]), toString(args[1]), toString(args[2])), nil
  3881. }
  3882. // Additional SQLite functions
  3883. case "PRINTF":
  3884. if len(args) > 0 {
  3885. format := toString(args[0])
  3886. fmtArgs := make([]interface{}, len(args)-1)
  3887. for i := 1; i < len(args); i++ {
  3888. fmtArgs[i-1] = args[i]
  3889. }
  3890. return fmt.Sprintf(format, fmtArgs...), nil
  3891. }
  3892. case "HEX":
  3893. if len(args) > 0 {
  3894. s := toString(args[0])
  3895. return strings.ToUpper(fmt.Sprintf("%x", []byte(s))), nil
  3896. }
  3897. case "UNHEX":
  3898. if len(args) > 0 {
  3899. s := toString(args[0])
  3900. var result []byte
  3901. for i := 0; i < len(s)-1; i += 2 {
  3902. var b byte
  3903. fmt.Sscanf(s[i:i+2], "%x", &b)
  3904. result = append(result, b)
  3905. }
  3906. return string(result), nil
  3907. }
  3908. case "RANDOM":
  3909. return rand.Int63(), nil
  3910. case "RANDOMBLOB":
  3911. if len(args) > 0 {
  3912. n := int(toFloat(args[0]))
  3913. if n <= 0 {
  3914. n = 1
  3915. }
  3916. if n > 1000000 {
  3917. n = 1000000
  3918. }
  3919. blob := make([]byte, n)
  3920. rand.Read(blob)
  3921. return string(blob), nil
  3922. }
  3923. case "ZEROBLOB":
  3924. if len(args) > 0 {
  3925. n := int(toFloat(args[0]))
  3926. if n <= 0 {
  3927. n = 1
  3928. }
  3929. if n > 1000000 {
  3930. n = 1000000
  3931. }
  3932. return string(make([]byte, n)), nil
  3933. }
  3934. case "INSTR":
  3935. if len(args) >= 2 {
  3936. s := toString(args[0])
  3937. substr := toString(args[1])
  3938. idx := strings.Index(s, substr)
  3939. if idx < 0 {
  3940. return int64(0), nil
  3941. }
  3942. return int64(idx + 1), nil // SQL is 1-indexed
  3943. }
  3944. case "GLOB":
  3945. if len(args) >= 2 {
  3946. pattern := toString(args[0])
  3947. s := toString(args[1])
  3948. return matchGlob(pattern, s), nil
  3949. }
  3950. case "ROUND":
  3951. if len(args) > 0 {
  3952. v := toFloat(args[0])
  3953. decimals := 0
  3954. if len(args) >= 2 {
  3955. decimals = int(toFloat(args[1]))
  3956. }
  3957. mult := 1.0
  3958. for i := 0; i < decimals; i++ {
  3959. mult *= 10
  3960. }
  3961. return float64(int64(v*mult+0.5)) / mult, nil
  3962. }
  3963. case "MAX":
  3964. if len(args) > 0 {
  3965. max := args[0]
  3966. for _, arg := range args[1:] {
  3967. if compare(arg, max) > 0 {
  3968. max = arg
  3969. }
  3970. }
  3971. return max, nil
  3972. }
  3973. case "MIN":
  3974. if len(args) > 0 {
  3975. min := args[0]
  3976. for _, arg := range args[1:] {
  3977. if compare(arg, min) < 0 {
  3978. min = arg
  3979. }
  3980. }
  3981. return min, nil
  3982. }
  3983. case "CONCAT":
  3984. var result strings.Builder
  3985. for _, arg := range args {
  3986. result.WriteString(toString(arg))
  3987. }
  3988. return result.String(), nil
  3989. // Date/Time functions
  3990. case "DATE":
  3991. return evalDateFunc(args)
  3992. case "TIME":
  3993. return evalTimeFunc(args)
  3994. case "DATETIME":
  3995. return evalDatetimeFunc(args)
  3996. case "JULIANDAY":
  3997. return evalJuliandayFunc(args)
  3998. case "UNIXEPOCH":
  3999. return evalUnixepochFunc(args)
  4000. case "STRFTIME":
  4001. return evalStrftimeFunc(args)
  4002. case "TIMEDIFF":
  4003. return evalTimediffFunc(args)
  4004. case "PIZZASQL_VERSION", "SQLITE_VERSION":
  4005. return version.String(), nil
  4006. case "LAST_INSERT_ROWID":
  4007. return e.lastInsertRowID, nil
  4008. case "CHANGES":
  4009. return e.changes, nil
  4010. case "TOTAL_CHANGES":
  4011. return e.totalChanges, nil
  4012. }
  4013. return nil, nil
  4014. }
  4015. func (e *Executor) evalCaseExpr(expr *parser.CaseExpr, row storage.Row) (interface{}, error) {
  4016. var operand interface{}
  4017. if expr.Operand != nil {
  4018. var err error
  4019. operand, err = e.evalExpr(expr.Operand, row)
  4020. if err != nil {
  4021. return nil, err
  4022. }
  4023. }
  4024. for _, when := range expr.Whens {
  4025. cond, err := e.evalExpr(when.Condition, row)
  4026. if err != nil {
  4027. return nil, err
  4028. }
  4029. var match bool
  4030. if expr.Operand != nil {
  4031. // Simple CASE: CASE operand WHEN val THEN ... — NULL operand matches nothing
  4032. if operand == nil {
  4033. continue
  4034. }
  4035. match = compare(operand, cond) == 0
  4036. } else {
  4037. // Searched CASE: CASE WHEN cond THEN ... — NULL condition is falsy
  4038. match = toBool(cond)
  4039. }
  4040. if match {
  4041. return e.evalExpr(when.Result, row)
  4042. }
  4043. }
  4044. if expr.Else != nil {
  4045. return e.evalExpr(expr.Else, row)
  4046. }
  4047. return nil, nil
  4048. }
  4049. func (e *Executor) evalInExpr(expr *parser.InExpr, row storage.Row) (interface{}, error) {
  4050. left, err := e.evalExpr(expr.Left, row)
  4051. if err != nil {
  4052. return nil, err
  4053. }
  4054. // Handle subquery: IN (SELECT ...)
  4055. if expr.Subquery != nil {
  4056. var result *Result
  4057. var err error
  4058. // Cache non-correlated subquery results for the duration of this query.
  4059. // Safe when outerRow is nil (no outer context that the subquery could reference).
  4060. if e.subqueryCache != nil && e.outerRow == nil {
  4061. if cached, ok := e.subqueryCache[expr.Subquery]; ok {
  4062. result = cached
  4063. } else {
  4064. result, err = e.executeSelect(expr.Subquery)
  4065. if err == nil {
  4066. e.subqueryCache[expr.Subquery] = result
  4067. }
  4068. }
  4069. } else {
  4070. result, err = e.executeSelect(expr.Subquery)
  4071. }
  4072. if err != nil {
  4073. return nil, fmt.Errorf("IN subquery error: %w", err)
  4074. }
  4075. if len(result.Columns) != 1 {
  4076. return nil, fmt.Errorf("subquery in IN must return exactly one column")
  4077. }
  4078. // SQL three-valued logic: if left is NULL → NULL; if any match → true; if any NULL → NULL; else false.
  4079. if left == nil {
  4080. return nil, nil
  4081. }
  4082. sawNull := false
  4083. for _, resultRow := range result.Rows {
  4084. if len(resultRow) == 0 {
  4085. continue
  4086. }
  4087. v := resultRow[0]
  4088. if v == nil {
  4089. sawNull = true
  4090. continue
  4091. }
  4092. if compare(left, v) == 0 {
  4093. if expr.Not {
  4094. return false, nil
  4095. }
  4096. return true, nil
  4097. }
  4098. }
  4099. if sawNull {
  4100. return nil, nil
  4101. }
  4102. if expr.Not {
  4103. return true, nil
  4104. }
  4105. return false, nil
  4106. }
  4107. // Handle value list: IN (1, 2, 3).
  4108. // Empty list: always FALSE (IN) / TRUE (NOT IN), even for NULL.
  4109. if len(expr.Values) == 0 {
  4110. return expr.Not, nil
  4111. }
  4112. // SQL three-valued logic: if left is NULL → NULL; if any match → true/false;
  4113. // if list contains NULL and no match → NULL.
  4114. if left == nil {
  4115. return nil, nil
  4116. }
  4117. sawNull := false
  4118. for _, val := range expr.Values {
  4119. v, err := e.evalExpr(val, row)
  4120. if err != nil {
  4121. return nil, err
  4122. }
  4123. if v == nil {
  4124. sawNull = true
  4125. continue
  4126. }
  4127. if compare(left, v) == 0 {
  4128. if expr.Not {
  4129. return false, nil
  4130. }
  4131. return true, nil
  4132. }
  4133. }
  4134. if sawNull {
  4135. return nil, nil
  4136. }
  4137. if expr.Not {
  4138. return true, nil
  4139. }
  4140. return false, nil
  4141. }
  4142. func (e *Executor) evalBetweenExpr(expr *parser.BetweenExpr, row storage.Row) (interface{}, error) {
  4143. val, err := e.evalExpr(expr.Left, row)
  4144. if err != nil {
  4145. return nil, err
  4146. }
  4147. low, err := e.evalExpr(expr.Low, row)
  4148. if err != nil {
  4149. return nil, err
  4150. }
  4151. high, err := e.evalExpr(expr.High, row)
  4152. if err != nil {
  4153. return nil, err
  4154. }
  4155. if expr.Not {
  4156. // NOT BETWEEN is equivalent to: val < low OR val > high
  4157. // We need to handle NULL using three-valued OR logic:
  4158. // NULL OR TRUE = TRUE
  4159. // NULL OR FALSE = NULL
  4160. // NULL OR NULL = NULL
  4161. var lessThan, greaterThan interface{}
  4162. if val == nil || low == nil {
  4163. lessThan = nil // NULL
  4164. } else {
  4165. lessThan = compare(val, low) < 0
  4166. }
  4167. if val == nil || high == nil {
  4168. greaterThan = nil // NULL
  4169. } else {
  4170. greaterThan = compare(val, high) > 0
  4171. }
  4172. // Implement three-valued OR
  4173. if toBool(lessThan) || toBool(greaterThan) {
  4174. return true, nil
  4175. }
  4176. if lessThan == nil || greaterThan == nil {
  4177. return nil, nil // NULL
  4178. }
  4179. return false, nil
  4180. } else {
  4181. // BETWEEN is equivalent to: val >= low AND val <= high
  4182. // Three-value logic: if val < low → FALSE (regardless of high); if val >= low and high is NULL → NULL
  4183. if val == nil {
  4184. return nil, nil
  4185. }
  4186. // x BETWEEN a AND b = (x >= a) AND (x <= b)
  4187. // NULL AND FALSE = FALSE; NULL AND TRUE = NULL
  4188. if low == nil {
  4189. // x >= NULL = NULL; check upper bound for early FALSE
  4190. if high != nil && compare(val, high) > 0 {
  4191. return false, nil // NULL AND FALSE = FALSE
  4192. }
  4193. return nil, nil // NULL AND TRUE/NULL = NULL
  4194. }
  4195. if compare(val, low) < 0 {
  4196. return false, nil // val < low → FALSE AND anything = FALSE
  4197. }
  4198. if high == nil {
  4199. return nil, nil // TRUE AND NULL = NULL
  4200. }
  4201. return compare(val, high) <= 0, nil
  4202. }
  4203. }
  4204. func (e *Executor) evalLikeExpr(expr *parser.LikeExpr, row storage.Row) (interface{}, error) {
  4205. val, err := e.evalExpr(expr.Left, row)
  4206. if err != nil {
  4207. return nil, err
  4208. }
  4209. pattern, err := e.evalExpr(expr.Pattern, row)
  4210. if err != nil {
  4211. return nil, err
  4212. }
  4213. s := toString(val)
  4214. p := toString(pattern)
  4215. // Convert SQL LIKE pattern to simple matching
  4216. // % matches any sequence, _ matches single character
  4217. matched := matchLike(s, p)
  4218. if expr.Not {
  4219. return !matched, nil
  4220. }
  4221. return matched, nil
  4222. }
  4223. func (e *Executor) evalIsNullExpr(expr *parser.IsNullExpr, row storage.Row) (interface{}, error) {
  4224. val, err := e.evalExpr(expr.Left, row)
  4225. if err != nil {
  4226. return nil, err
  4227. }
  4228. isNull := val == nil
  4229. if expr.Not {
  4230. return !isNull, nil
  4231. }
  4232. return isNull, nil
  4233. }
  4234. func (e *Executor) evalCastExpr(expr *parser.CastExpr, row storage.Row) (interface{}, error) {
  4235. val, err := e.evalExpr(expr.Expr, row)
  4236. if err != nil {
  4237. return nil, err
  4238. }
  4239. if val == nil {
  4240. return nil, nil // CAST(NULL AS any) = NULL
  4241. }
  4242. typeName := strings.ToUpper(expr.Type.Name)
  4243. switch {
  4244. case strings.Contains(typeName, "INT"):
  4245. return int64(toFloat(val)), nil
  4246. case strings.Contains(typeName, "REAL"), strings.Contains(typeName, "FLOAT"), strings.Contains(typeName, "DOUBLE"):
  4247. return toFloat(val), nil
  4248. case strings.Contains(typeName, "TEXT"), strings.Contains(typeName, "CHAR"):
  4249. return toString(val), nil
  4250. default:
  4251. return val, nil
  4252. }
  4253. }
  4254. // evalSubqueryExpr executes a scalar subquery and returns its value.
  4255. // A scalar subquery must return exactly one column. It returns:
  4256. // - The single value if the subquery returns one row
  4257. // - NULL if the subquery returns no rows
  4258. // - Error if the subquery returns more than one row (for strict SQL compliance)
  4259. func (e *Executor) evalSubqueryExpr(expr *parser.SubqueryExpr, row storage.Row) (interface{}, error) {
  4260. if row != nil && e.correlatedAggCache != nil {
  4261. if val, ok, err := e.evalDecorrelatedAggSubquery(expr.Query, row); ok || err != nil {
  4262. return val, err
  4263. }
  4264. }
  4265. // Save and set outer row context for correlated subqueries
  4266. savedOuter := e.outerRow
  4267. e.outerRow = row
  4268. defer func() { e.outerRow = savedOuter }()
  4269. // Execute the subquery
  4270. result, err := e.executeSelect(expr.Query)
  4271. if err != nil {
  4272. return nil, fmt.Errorf("subquery error: %w", err)
  4273. }
  4274. // Check for empty result
  4275. if result.RowCount == 0 {
  4276. return nil, nil // Return NULL for empty subquery
  4277. }
  4278. // Check column count
  4279. if len(result.Columns) == 0 {
  4280. return nil, fmt.Errorf("subquery must return at least one column")
  4281. }
  4282. // For scalar subquery, return first column of first row
  4283. // Note: Strict SQL would error if more than one row is returned
  4284. // but we follow SQLite behavior which just returns the first value
  4285. if len(result.Rows) > 0 && len(result.Rows[0]) > 0 {
  4286. return result.Rows[0][0], nil
  4287. }
  4288. return nil, nil
  4289. }
  4290. func (e *Executor) evalDecorrelatedAggSubquery(query *parser.SelectStmt, outerRow storage.Row) (interface{}, bool, error) {
  4291. spec, ok := e.correlatedAggSpec(query)
  4292. if !ok {
  4293. return nil, false, nil
  4294. }
  4295. outerVal, err := e.evalExpr(spec.outerKey, outerRow)
  4296. if err != nil {
  4297. return nil, true, err
  4298. }
  4299. cache, exists := e.correlatedAggCache[query]
  4300. if !exists {
  4301. cache, err = e.buildCorrelatedAggCache(query, spec)
  4302. if err != nil {
  4303. return nil, true, err
  4304. }
  4305. e.correlatedAggCache[query] = cache
  4306. }
  4307. if outerVal == nil {
  4308. return cache.defaultValue, true, nil
  4309. }
  4310. if val, exists := cache.values[fmt.Sprintf("%v", outerVal)]; exists {
  4311. return val, true, nil
  4312. }
  4313. return cache.defaultValue, true, nil
  4314. }
  4315. func (e *Executor) correlatedAggSpec(query *parser.SelectStmt) (correlatedAggSpec, bool) {
  4316. if query == nil ||
  4317. query.Compound != nil ||
  4318. len(query.Columns) != 1 ||
  4319. len(query.From) == 0 ||
  4320. query.Where == nil ||
  4321. len(query.GroupBy) > 0 ||
  4322. query.Having != nil ||
  4323. query.Limit != nil ||
  4324. query.Offset != nil {
  4325. return correlatedAggSpec{}, false
  4326. }
  4327. if query.Columns[0].Star {
  4328. return correlatedAggSpec{}, false
  4329. }
  4330. agg, ok := query.Columns[0].Expr.(*parser.FunctionCall)
  4331. if !ok {
  4332. return correlatedAggSpec{}, false
  4333. }
  4334. switch strings.ToUpper(agg.Name) {
  4335. case "COUNT", "SUM", "AVG", "MIN", "MAX":
  4336. default:
  4337. return correlatedAggSpec{}, false
  4338. }
  4339. innerAliases := collectFromAliases(query.From)
  4340. bin, ok := query.Where.(*parser.BinaryExpr)
  4341. if !ok || bin.Op != lexer.TokenEq {
  4342. return correlatedAggSpec{}, false
  4343. }
  4344. leftRef, leftIsRef := bin.Left.(*parser.ColumnRef)
  4345. rightRef, rightIsRef := bin.Right.(*parser.ColumnRef)
  4346. if !leftIsRef || !rightIsRef {
  4347. return correlatedAggSpec{}, false
  4348. }
  4349. leftInner := refBelongsToAliases(leftRef, innerAliases)
  4350. rightInner := refBelongsToAliases(rightRef, innerAliases)
  4351. if leftInner == rightInner {
  4352. return correlatedAggSpec{}, false
  4353. }
  4354. if leftInner {
  4355. return correlatedAggSpec{innerKey: leftRef, outerKey: rightRef, aggExpr: agg}, true
  4356. }
  4357. return correlatedAggSpec{innerKey: rightRef, outerKey: leftRef, aggExpr: agg}, true
  4358. }
  4359. func (e *Executor) buildCorrelatedAggCache(query *parser.SelectStmt, spec correlatedAggSpec) (*correlatedAggCache, error) {
  4360. grouped := *query
  4361. grouped.Where = nil
  4362. grouped.GroupBy = []parser.Expr{spec.innerKey}
  4363. grouped.Having = nil
  4364. grouped.OrderBy = nil
  4365. grouped.Limit = nil
  4366. grouped.Offset = nil
  4367. grouped.Columns = []parser.SelectColumn{
  4368. {Expr: spec.innerKey, Alias: "__corr_key"},
  4369. {Expr: spec.aggExpr, Alias: "__corr_value"},
  4370. }
  4371. savedOuter := e.outerRow
  4372. e.outerRow = nil
  4373. result, err := e.executeSelect(&grouped)
  4374. e.outerRow = savedOuter
  4375. if err != nil {
  4376. return nil, fmt.Errorf("decorrelated aggregate subquery error: %w", err)
  4377. }
  4378. cache := &correlatedAggCache{
  4379. values: make(map[string]interface{}, len(result.Rows)),
  4380. defaultValue: correlatedAggDefault(spec.aggExpr),
  4381. }
  4382. for _, row := range result.Rows {
  4383. if len(row) < 2 || row[0] == nil {
  4384. continue
  4385. }
  4386. cache.values[fmt.Sprintf("%v", row[0])] = row[1]
  4387. }
  4388. return cache, nil
  4389. }
  4390. func correlatedAggDefault(expr parser.Expr) interface{} {
  4391. if fn, ok := expr.(*parser.FunctionCall); ok && strings.EqualFold(fn.Name, "COUNT") {
  4392. return int64(0)
  4393. }
  4394. return nil
  4395. }
  4396. func collectFromAliases(from []parser.TableRef) map[string]struct{} {
  4397. aliases := make(map[string]struct{})
  4398. var addRef func(parser.TableRef)
  4399. addRef = func(ref parser.TableRef) {
  4400. if ref.Name != "" {
  4401. aliases[strings.ToLower(ref.Name)] = struct{}{}
  4402. }
  4403. if ref.Alias != "" {
  4404. aliases[strings.ToLower(ref.Alias)] = struct{}{}
  4405. }
  4406. if ref.Join != nil && ref.Join.Table != nil {
  4407. addRef(*ref.Join.Table)
  4408. }
  4409. }
  4410. for _, ref := range from {
  4411. addRef(ref)
  4412. }
  4413. return aliases
  4414. }
  4415. func refBelongsToAliases(ref *parser.ColumnRef, aliases map[string]struct{}) bool {
  4416. if ref == nil || ref.Table == "" {
  4417. return false
  4418. }
  4419. _, ok := aliases[strings.ToLower(ref.Table)]
  4420. return ok
  4421. }
  4422. // evalExistsExpr evaluates an EXISTS expression.
  4423. // Returns true if the subquery returns at least one row, false otherwise.
  4424. func (e *Executor) evalExistsExpr(expr *parser.ExistsExpr, row storage.Row) (interface{}, error) {
  4425. // Save and set outer row context for correlated subqueries
  4426. savedOuter := e.outerRow
  4427. e.outerRow = row
  4428. defer func() { e.outerRow = savedOuter }()
  4429. // Execute the subquery
  4430. result, err := e.executeSelect(expr.Subquery)
  4431. if err != nil {
  4432. return nil, fmt.Errorf("EXISTS subquery error: %w", err)
  4433. }
  4434. // EXISTS returns true if any rows are returned
  4435. return len(result.Rows) > 0, nil
  4436. }
  4437. // evalAggregateExpr evaluates an aggregate expression over multiple rows.
  4438. func (e *Executor) evalAggregateExpr(expr parser.Expr, rows []storage.Row) (interface{}, error) {
  4439. fn, ok := expr.(*parser.FunctionCall)
  4440. if !ok {
  4441. // Not a function call - could be a binary expression with aggregates inside
  4442. // Evaluate it with the aggregate evaluation context
  4443. return e.evalExprWithAggregates(expr, rows)
  4444. }
  4445. name := strings.ToUpper(fn.Name)
  4446. switch name {
  4447. case "COUNT":
  4448. if fn.Star {
  4449. return int64(len(rows)), nil
  4450. }
  4451. if fn.Distinct {
  4452. seen := make(map[interface{}]struct{})
  4453. for _, row := range rows {
  4454. if len(fn.Args) > 0 {
  4455. val, _ := e.evalExpr(fn.Args[0], row)
  4456. if val != nil {
  4457. seen[val] = struct{}{}
  4458. }
  4459. }
  4460. }
  4461. return int64(len(seen)), nil
  4462. }
  4463. count := int64(0)
  4464. for _, row := range rows {
  4465. if len(fn.Args) > 0 {
  4466. val, _ := e.evalExpr(fn.Args[0], row)
  4467. if val != nil {
  4468. count++
  4469. }
  4470. }
  4471. }
  4472. return count, nil
  4473. case "SUM":
  4474. var sumInt int64
  4475. var sumFloat float64
  4476. allInt := true
  4477. hasValues := false
  4478. var seen map[interface{}]struct{}
  4479. if fn.Distinct {
  4480. seen = make(map[interface{}]struct{})
  4481. }
  4482. for _, row := range rows {
  4483. if len(fn.Args) > 0 {
  4484. val, _ := e.evalExpr(fn.Args[0], row)
  4485. if val != nil {
  4486. if fn.Distinct {
  4487. key := fmt.Sprintf("%v", val)
  4488. if _, exists := seen[key]; exists {
  4489. continue
  4490. }
  4491. seen[key] = struct{}{}
  4492. }
  4493. if isIntVal(val) {
  4494. sumInt += toInt64(val)
  4495. } else {
  4496. allInt = false
  4497. sumFloat += toFloat(val)
  4498. }
  4499. hasValues = true
  4500. }
  4501. }
  4502. }
  4503. if !hasValues {
  4504. return nil, nil
  4505. }
  4506. if allInt {
  4507. return sumInt, nil
  4508. }
  4509. return sumFloat + float64(sumInt), nil
  4510. case "AVG":
  4511. var sum float64
  4512. count := 0
  4513. for _, row := range rows {
  4514. if len(fn.Args) > 0 {
  4515. val, _ := e.evalExpr(fn.Args[0], row)
  4516. if val != nil {
  4517. sum += toFloat(val)
  4518. count++
  4519. }
  4520. }
  4521. }
  4522. if count == 0 {
  4523. return nil, nil
  4524. }
  4525. return sum / float64(count), nil
  4526. case "MIN":
  4527. var min interface{}
  4528. for _, row := range rows {
  4529. if len(fn.Args) > 0 {
  4530. val, _ := e.evalExpr(fn.Args[0], row)
  4531. if val != nil && (min == nil || compare(val, min) < 0) {
  4532. min = val
  4533. }
  4534. }
  4535. }
  4536. return min, nil
  4537. case "MAX":
  4538. var max interface{}
  4539. for _, row := range rows {
  4540. if len(fn.Args) > 0 {
  4541. val, _ := e.evalExpr(fn.Args[0], row)
  4542. if val != nil && (max == nil || compare(val, max) > 0) {
  4543. max = val
  4544. }
  4545. }
  4546. }
  4547. return max, nil
  4548. default:
  4549. // Non-aggregate scalar function: evaluate args through aggregate context
  4550. // (so COUNT/MIN/etc. inside NULLIF/COALESCE work correctly).
  4551. return e.evalExprWithAggregates(expr, rows)
  4552. }
  4553. }
  4554. // evalExprWithAggregates evaluates an expression that may contain aggregate functions
  4555. func (e *Executor) evalExprWithAggregates(expr parser.Expr, rows []storage.Row) (interface{}, error) {
  4556. switch ex := expr.(type) {
  4557. case *parser.BinaryExpr:
  4558. left, err := e.evalExprWithAggregates(ex.Left, rows)
  4559. if err != nil {
  4560. return nil, err
  4561. }
  4562. right, err := e.evalExprWithAggregates(ex.Right, rows)
  4563. if err != nil {
  4564. return nil, err
  4565. }
  4566. // Use the same logic as evalBinaryExpr to preserve integer semantics.
  4567. combined := &parser.BinaryExpr{Op: ex.Op}
  4568. return e.applyBinaryOp(combined.Op, left, right)
  4569. case *parser.FunctionCall:
  4570. name := strings.ToUpper(ex.Name)
  4571. switch name {
  4572. case "COUNT", "SUM", "AVG", "MIN", "MAX", "TOTAL", "GROUP_CONCAT":
  4573. return e.evalAggregateExpr(expr, rows)
  4574. default:
  4575. // Non-aggregate: evaluate each arg with aggregate context, then apply scalar.
  4576. args := make([]interface{}, len(ex.Args))
  4577. for i, arg := range ex.Args {
  4578. v, err := e.evalExprWithAggregates(arg, rows)
  4579. if err != nil {
  4580. return nil, err
  4581. }
  4582. args[i] = v
  4583. }
  4584. return e.evalBuiltinFunction(name, args)
  4585. }
  4586. case *parser.ParenExpr:
  4587. return e.evalExprWithAggregates(ex.Expr, rows)
  4588. case *parser.UnaryExpr:
  4589. operand, err := e.evalExprWithAggregates(ex.Operand, rows)
  4590. if err != nil {
  4591. return nil, err
  4592. }
  4593. switch ex.Op {
  4594. case lexer.TokenPlus:
  4595. return operand, nil
  4596. case lexer.TokenMinus:
  4597. if operand == nil {
  4598. return nil, nil
  4599. }
  4600. if isIntVal(operand) {
  4601. return -toInt64(operand), nil
  4602. }
  4603. return -toFloat(operand), nil
  4604. case lexer.TokenNOT:
  4605. if operand == nil {
  4606. return nil, nil // NOT NULL = NULL
  4607. }
  4608. return !toBool(operand), nil
  4609. default:
  4610. return nil, fmt.Errorf("unsupported unary operator: %v", ex.Op)
  4611. }
  4612. case *parser.CastExpr:
  4613. // Evaluate inner expression with aggregate context, then apply cast.
  4614. val, err := e.evalExprWithAggregates(ex.Expr, rows)
  4615. if err != nil {
  4616. return nil, err
  4617. }
  4618. if val == nil {
  4619. return nil, nil
  4620. }
  4621. switch strings.ToUpper(ex.Type.Name) {
  4622. case "INTEGER", "INT", "BIGINT", "SMALLINT", "TINYINT", "SIGNED":
  4623. if isIntVal(val) {
  4624. return toInt64(val), nil
  4625. }
  4626. return int64(toFloat(val)), nil
  4627. case "REAL", "FLOAT", "DOUBLE", "NUMERIC", "DECIMAL":
  4628. return toFloat(val), nil
  4629. case "TEXT", "VARCHAR", "CHAR", "STRING":
  4630. return fmt.Sprintf("%v", val), nil
  4631. }
  4632. return val, nil
  4633. case *parser.CaseExpr:
  4634. var operand interface{}
  4635. if ex.Operand != nil {
  4636. operand, _ = e.evalExprWithAggregates(ex.Operand, rows)
  4637. }
  4638. for _, when := range ex.Whens {
  4639. condVal, _ := e.evalExprWithAggregates(when.Condition, rows)
  4640. var matched bool
  4641. if ex.Operand != nil {
  4642. matched = operand != nil && condVal != nil && compare(operand, condVal) == 0
  4643. } else {
  4644. matched = toBool(condVal)
  4645. }
  4646. if matched {
  4647. return e.evalExprWithAggregates(when.Result, rows)
  4648. }
  4649. }
  4650. if ex.Else != nil {
  4651. return e.evalExprWithAggregates(ex.Else, rows)
  4652. }
  4653. return nil, nil
  4654. case *parser.IsNullExpr:
  4655. val, err := e.evalExprWithAggregates(ex.Left, rows)
  4656. if err != nil {
  4657. return nil, err
  4658. }
  4659. isNull := val == nil
  4660. if ex.Not {
  4661. return !isNull, nil
  4662. }
  4663. return isNull, nil
  4664. case *parser.BetweenExpr:
  4665. val, err := e.evalExprWithAggregates(ex.Left, rows)
  4666. if err != nil {
  4667. return nil, err
  4668. }
  4669. low, err := e.evalExprWithAggregates(ex.Low, rows)
  4670. if err != nil {
  4671. return nil, err
  4672. }
  4673. high, err := e.evalExprWithAggregates(ex.High, rows)
  4674. if err != nil {
  4675. return nil, err
  4676. }
  4677. if ex.Not {
  4678. // NOT BETWEEN: val < low OR val > high
  4679. var lessThan, greaterThan interface{}
  4680. if val == nil || low == nil {
  4681. lessThan = nil
  4682. } else {
  4683. lessThan = compare(val, low) < 0
  4684. }
  4685. if val == nil || high == nil {
  4686. greaterThan = nil
  4687. } else {
  4688. greaterThan = compare(val, high) > 0
  4689. }
  4690. // Three-valued OR
  4691. if toBool(lessThan) || toBool(greaterThan) {
  4692. return true, nil
  4693. }
  4694. if lessThan == nil || greaterThan == nil {
  4695. return nil, nil
  4696. }
  4697. return false, nil
  4698. } else {
  4699. // BETWEEN: val >= low AND val <= high
  4700. if val == nil {
  4701. return nil, nil
  4702. }
  4703. if low == nil {
  4704. if high != nil && compare(val, high) > 0 {
  4705. return false, nil
  4706. }
  4707. return nil, nil
  4708. }
  4709. if compare(val, low) < 0 {
  4710. return false, nil
  4711. }
  4712. if high == nil {
  4713. return nil, nil
  4714. }
  4715. return compare(val, high) <= 0, nil
  4716. }
  4717. case *parser.InExpr:
  4718. left, err := e.evalExprWithAggregates(ex.Left, rows)
  4719. if err != nil {
  4720. return nil, err
  4721. }
  4722. // Handle subquery
  4723. if ex.Subquery != nil {
  4724. var result *Result
  4725. var err error
  4726. if e.subqueryCache != nil && e.outerRow == nil {
  4727. if cached, ok := e.subqueryCache[ex.Subquery]; ok {
  4728. result = cached
  4729. } else {
  4730. result, err = e.executeSelect(ex.Subquery)
  4731. if err == nil {
  4732. e.subqueryCache[ex.Subquery] = result
  4733. }
  4734. }
  4735. } else {
  4736. result, err = e.executeSelect(ex.Subquery)
  4737. }
  4738. if err != nil {
  4739. return nil, fmt.Errorf("IN subquery error: %w", err)
  4740. }
  4741. if len(result.Columns) != 1 {
  4742. return nil, fmt.Errorf("subquery in IN must return exactly one column")
  4743. }
  4744. if left == nil {
  4745. return nil, nil
  4746. }
  4747. sawNull := false
  4748. for _, resultRow := range result.Rows {
  4749. if len(resultRow) == 0 {
  4750. continue
  4751. }
  4752. v := resultRow[0]
  4753. if v == nil {
  4754. sawNull = true
  4755. continue
  4756. }
  4757. if compare(left, v) == 0 {
  4758. if ex.Not {
  4759. return false, nil
  4760. }
  4761. return true, nil
  4762. }
  4763. }
  4764. if sawNull {
  4765. return nil, nil
  4766. }
  4767. if ex.Not {
  4768. return true, nil
  4769. }
  4770. return false, nil
  4771. }
  4772. // Handle value list
  4773. if len(ex.Values) == 0 {
  4774. return ex.Not, nil
  4775. }
  4776. if left == nil {
  4777. return nil, nil
  4778. }
  4779. sawNull := false
  4780. for _, val := range ex.Values {
  4781. v, err := e.evalExprWithAggregates(val, rows)
  4782. if err != nil {
  4783. return nil, err
  4784. }
  4785. if v == nil {
  4786. sawNull = true
  4787. continue
  4788. }
  4789. if compare(left, v) == 0 {
  4790. if ex.Not {
  4791. return false, nil
  4792. }
  4793. return true, nil
  4794. }
  4795. }
  4796. if sawNull {
  4797. return nil, nil
  4798. }
  4799. if ex.Not {
  4800. return true, nil
  4801. }
  4802. return false, nil
  4803. default:
  4804. // Literals and non-aggregate expressions.
  4805. if len(rows) > 0 {
  4806. return e.evalExpr(expr, rows[0])
  4807. }
  4808. return e.evalExpr(expr, storage.Row{})
  4809. }
  4810. }
  4811. // Helper functions
  4812. func (e *Executor) getSelectColumns(stmt *parser.SelectStmt, schema *storage.Schema) []string {
  4813. var columns []string
  4814. for _, col := range stmt.Columns {
  4815. if col.Star {
  4816. for _, c := range schema.Columns {
  4817. columns = append(columns, c.Name)
  4818. }
  4819. } else if col.Alias != "" {
  4820. columns = append(columns, col.Alias)
  4821. } else if ref, ok := col.Expr.(*parser.ColumnRef); ok {
  4822. columns = append(columns, ref.Column)
  4823. } else {
  4824. columns = append(columns, fmt.Sprintf("column%d", len(columns)+1))
  4825. }
  4826. }
  4827. return columns
  4828. }
  4829. func (e *Executor) hasAggregates(columns []parser.SelectColumn) bool {
  4830. for _, col := range columns {
  4831. if e.isAggregate(col.Expr) {
  4832. return true
  4833. }
  4834. }
  4835. return false
  4836. }
  4837. func (e *Executor) isAggregate(expr parser.Expr) bool {
  4838. if fn, ok := expr.(*parser.FunctionCall); ok {
  4839. name := strings.ToUpper(fn.Name)
  4840. switch name {
  4841. case "COUNT", "SUM", "AVG", "MIN", "MAX", "TOTAL", "GROUP_CONCAT":
  4842. return true
  4843. }
  4844. // Non-aggregate function: check if any arg contains an aggregate.
  4845. for _, arg := range fn.Args {
  4846. if e.isAggregate(arg) {
  4847. return true
  4848. }
  4849. }
  4850. return false
  4851. }
  4852. switch ex := expr.(type) {
  4853. case *parser.UnaryExpr:
  4854. return e.isAggregate(ex.Operand)
  4855. case *parser.BinaryExpr:
  4856. return e.isAggregate(ex.Left) || e.isAggregate(ex.Right)
  4857. case *parser.ParenExpr:
  4858. return e.isAggregate(ex.Expr)
  4859. case *parser.CaseExpr:
  4860. if ex.Operand != nil && e.isAggregate(ex.Operand) {
  4861. return true
  4862. }
  4863. for _, w := range ex.Whens {
  4864. if e.isAggregate(w.Condition) || e.isAggregate(w.Result) {
  4865. return true
  4866. }
  4867. }
  4868. if ex.Else != nil {
  4869. return e.isAggregate(ex.Else)
  4870. }
  4871. case *parser.CastExpr:
  4872. return e.isAggregate(ex.Expr)
  4873. case *parser.IsNullExpr:
  4874. return e.isAggregate(ex.Left)
  4875. case *parser.BetweenExpr:
  4876. return e.isAggregate(ex.Left) || e.isAggregate(ex.Low) || e.isAggregate(ex.High)
  4877. case *parser.InExpr:
  4878. if e.isAggregate(ex.Left) {
  4879. return true
  4880. }
  4881. for _, val := range ex.Values {
  4882. if e.isAggregate(val) {
  4883. return true
  4884. }
  4885. }
  4886. return false
  4887. }
  4888. return false
  4889. }
  4890. func (e *Executor) buildGroupKey(groupBy []parser.Expr, row storage.Row) string {
  4891. var parts []string
  4892. for _, expr := range groupBy {
  4893. val, _ := e.evalExpr(expr, row)
  4894. parts = append(parts, fmt.Sprintf("%v", val))
  4895. }
  4896. return strings.Join(parts, "|")
  4897. }
  4898. // resolveOrderByPositions replaces positional ORDER BY expressions (e.g. ORDER BY 1)
  4899. // with the corresponding SELECT column expressions per SQL-92 semantics.
  4900. func resolveOrderByPositions(orderBy []parser.OrderByItem, selectCols []parser.SelectColumn) []parser.OrderByItem {
  4901. result := make([]parser.OrderByItem, len(orderBy))
  4902. for i, item := range orderBy {
  4903. if lit, ok := item.Expr.(*parser.LiteralExpr); ok {
  4904. if pos, err := strconv.Atoi(lit.Value); err == nil && pos >= 1 && pos <= len(selectCols) {
  4905. col := selectCols[pos-1]
  4906. if col.Expr != nil {
  4907. result[i] = parser.OrderByItem{Expr: col.Expr, Desc: item.Desc}
  4908. continue
  4909. }
  4910. }
  4911. }
  4912. result[i] = item
  4913. }
  4914. return result
  4915. }
  4916. // orderByLess reports whether key slice a sorts before b under orderBy.
  4917. // Keys are precomputed per-row ORDER BY expression values, one per item.
  4918. func orderByLess(a, b []interface{}, orderBy []parser.OrderByItem) bool {
  4919. for i, item := range orderBy {
  4920. cmp := compare(a[i], b[i])
  4921. if cmp != 0 {
  4922. if item.Desc {
  4923. return cmp > 0
  4924. }
  4925. return cmp < 0
  4926. }
  4927. }
  4928. return false
  4929. }
  4930. // sortKeyOrder returns a permutation of [0..len(keys)) that sorts the keys
  4931. // ascending per orderBy.
  4932. func sortKeyOrder(keys [][]interface{}, orderBy []parser.OrderByItem) []int {
  4933. order := make([]int, len(keys))
  4934. for i := range order {
  4935. order[i] = i
  4936. }
  4937. sort.Slice(order, func(a, b int) bool {
  4938. return orderByLess(keys[order[a]], keys[order[b]], orderBy)
  4939. })
  4940. return order
  4941. }
  4942. // topNHeap is a bounded max-heap that keeps the k smallest elements (per
  4943. // orderByLess) seen so far.
  4944. type topNHeap struct {
  4945. keys [][]interface{}
  4946. idx []int
  4947. orderBy []parser.OrderByItem
  4948. }
  4949. func (h *topNHeap) Len() int { return len(h.idx) }
  4950. func (h *topNHeap) Less(i, j int) bool {
  4951. return orderByLess(h.keys[h.idx[j]], h.keys[h.idx[i]], h.orderBy)
  4952. }
  4953. func (h *topNHeap) Swap(i, j int) { h.idx[i], h.idx[j] = h.idx[j], h.idx[i] }
  4954. func (h *topNHeap) Push(x interface{}) { h.idx = append(h.idx, x.(int)) }
  4955. func (h *topNHeap) Pop() interface{} {
  4956. n := len(h.idx)
  4957. x := h.idx[n-1]
  4958. h.idx = h.idx[:n-1]
  4959. return x
  4960. }
  4961. // topNKeyOrder returns the indices of the k smallest keys (per orderByLess) in
  4962. // ascending order, without fully sorting all n elements. If k >= n it falls
  4963. // back to a full sort.
  4964. func topNKeyOrder(keys [][]interface{}, orderBy []parser.OrderByItem, k int) []int {
  4965. if k <= 0 {
  4966. return nil
  4967. }
  4968. if k >= len(keys) {
  4969. return sortKeyOrder(keys, orderBy)
  4970. }
  4971. h := &topNHeap{keys: keys, orderBy: orderBy, idx: make([]int, 0, k)}
  4972. for i := range keys {
  4973. if h.Len() < k {
  4974. heap.Push(h, i)
  4975. } else if orderByLess(keys[i], keys[h.idx[0]], orderBy) {
  4976. h.idx[0] = i
  4977. heap.Fix(h, 0)
  4978. }
  4979. }
  4980. selected := append([]int(nil), h.idx...)
  4981. sort.Slice(selected, func(a, b int) bool {
  4982. return orderByLess(keys[selected[a]], keys[selected[b]], orderBy)
  4983. })
  4984. return selected
  4985. }
  4986. func reorderRows(rows []storage.Row, order []int) {
  4987. tmp := make([]storage.Row, len(rows))
  4988. for i, idx := range order {
  4989. tmp[i] = rows[idx]
  4990. }
  4991. copy(rows, tmp)
  4992. }
  4993. // sortRowKeys precomputes the ORDER BY expression value for each row so each
  4994. // expression is evaluated once per row instead of O(n log n) times.
  4995. func (e *Executor) sortRowKeys(rows []storage.Row, orderBy []parser.OrderByItem) [][]interface{} {
  4996. keys := make([][]interface{}, len(rows))
  4997. for i, row := range rows {
  4998. ks := make([]interface{}, len(orderBy))
  4999. for j, item := range orderBy {
  5000. ks[j], _ = e.evalExpr(item.Expr, row)
  5001. }
  5002. keys[i] = ks
  5003. }
  5004. return keys
  5005. }
  5006. func (e *Executor) sortRows(rows []storage.Row, orderBy []parser.OrderByItem) {
  5007. order := sortKeyOrder(e.sortRowKeys(rows, orderBy), orderBy)
  5008. reorderRows(rows, order)
  5009. }
  5010. // topNRows sorts only enough to keep the k smallest rows (per orderBy).
  5011. func (e *Executor) topNRows(rows []storage.Row, orderBy []parser.OrderByItem, k int) []storage.Row {
  5012. order := topNKeyOrder(e.sortRowKeys(rows, orderBy), orderBy, k)
  5013. out := make([]storage.Row, len(order))
  5014. for i, idx := range order {
  5015. out[i] = rows[idx]
  5016. }
  5017. return out
  5018. }
  5019. // orderAndLimitRows applies ORDER BY (with a bounded top-N selection when a
  5020. // LIMIT is present), then OFFSET and LIMIT, preserving SQL semantics.
  5021. func (e *Executor) orderAndLimitRows(rows []storage.Row, orderBy []parser.OrderByItem, limitExpr, offsetExpr parser.Expr, selectCols []parser.SelectColumn) []storage.Row {
  5022. orderBy = resolveOrderByPositions(orderBy, selectCols)
  5023. var offset, limit int
  5024. hasOffset := offsetExpr != nil
  5025. hasLimit := limitExpr != nil
  5026. if hasOffset {
  5027. offset = e.evalIntExpr(offsetExpr)
  5028. }
  5029. if hasLimit {
  5030. limit = e.evalIntExpr(limitExpr)
  5031. }
  5032. if len(orderBy) > 0 {
  5033. if hasLimit && limit >= 0 {
  5034. k := offset + limit
  5035. if k >= 0 && k < len(rows) {
  5036. rows = e.topNRows(rows, orderBy, k)
  5037. } else {
  5038. e.sortRows(rows, orderBy)
  5039. }
  5040. } else {
  5041. e.sortRows(rows, orderBy)
  5042. }
  5043. }
  5044. if hasOffset {
  5045. if offset < len(rows) {
  5046. rows = rows[offset:]
  5047. } else {
  5048. rows = nil
  5049. }
  5050. }
  5051. if hasLimit {
  5052. if limit < len(rows) {
  5053. rows = rows[:limit]
  5054. }
  5055. }
  5056. return rows
  5057. }
  5058. // resultRowKey evaluates a single ORDER BY item against a result row, honoring
  5059. // select-column aliases exactly like the previous sortResultRows implementation.
  5060. func (e *Executor) resultRowKey(result *Result, rowIdx int, item parser.OrderByItem, columnNames []string) interface{} {
  5061. if ref, ok := item.Expr.(*parser.ColumnRef); ok && ref.Table == "" {
  5062. for idx, name := range columnNames {
  5063. if strings.EqualFold(name, ref.Column) {
  5064. if idx < len(result.Rows[rowIdx]) {
  5065. return result.Rows[rowIdx][idx]
  5066. }
  5067. }
  5068. }
  5069. }
  5070. row := e.resultRowToStorageRow(result, rowIdx)
  5071. v, _ := e.evalExpr(item.Expr, row)
  5072. return v
  5073. }
  5074. // resultRowKeys precomputes the ORDER BY expression value for each result row.
  5075. func (e *Executor) resultRowKeys(result *Result, orderBy []parser.OrderByItem, columnNames []string) [][]interface{} {
  5076. keys := make([][]interface{}, len(result.Rows))
  5077. for i := range result.Rows {
  5078. ks := make([]interface{}, len(orderBy))
  5079. for j, item := range orderBy {
  5080. ks[j] = e.resultRowKey(result, i, item, columnNames)
  5081. }
  5082. keys[i] = ks
  5083. }
  5084. return keys
  5085. }
  5086. // sortResultRows sorts Result.Rows based on ORDER BY clauses.
  5087. // It handles column aliases by matching them against the select columns.
  5088. func (e *Executor) sortResultRows(result *Result, orderBy []parser.OrderByItem, selectColumns []parser.SelectColumn, columnNames []string) {
  5089. orderBy = resolveOrderByPositions(orderBy, selectColumns)
  5090. order := sortKeyOrder(e.resultRowKeys(result, orderBy, columnNames), orderBy)
  5091. rows := make([][]interface{}, len(order))
  5092. for i, idx := range order {
  5093. rows[i] = result.Rows[idx]
  5094. }
  5095. result.Rows = rows
  5096. }
  5097. // orderAndLimitResultRows applies ORDER BY (with bounded top-N selection when a
  5098. // LIMIT is present), then OFFSET and LIMIT, to a Result's rows.
  5099. func (e *Executor) orderAndLimitResultRows(result *Result, orderBy []parser.OrderByItem, limitExpr, offsetExpr parser.Expr, selectCols []parser.SelectColumn, columnNames []string) {
  5100. orderBy = resolveOrderByPositions(orderBy, selectCols)
  5101. var offset, limit int
  5102. hasOffset := offsetExpr != nil
  5103. hasLimit := limitExpr != nil
  5104. if hasOffset {
  5105. offset = e.evalIntExpr(offsetExpr)
  5106. }
  5107. if hasLimit {
  5108. limit = e.evalIntExpr(limitExpr)
  5109. }
  5110. if len(orderBy) > 0 {
  5111. if hasLimit && limit >= 0 {
  5112. k := offset + limit
  5113. if k >= 0 && k < len(result.Rows) {
  5114. order := topNKeyOrder(e.resultRowKeys(result, orderBy, columnNames), orderBy, k)
  5115. rows := make([][]interface{}, len(order))
  5116. for i, idx := range order {
  5117. rows[i] = result.Rows[idx]
  5118. }
  5119. result.Rows = rows
  5120. } else {
  5121. e.sortResultRows(result, orderBy, nil, columnNames)
  5122. }
  5123. } else {
  5124. e.sortResultRows(result, orderBy, nil, columnNames)
  5125. }
  5126. }
  5127. if hasOffset {
  5128. if offset < len(result.Rows) {
  5129. result.Rows = result.Rows[offset:]
  5130. } else {
  5131. result.Rows = nil
  5132. }
  5133. result.RowCount = len(result.Rows)
  5134. }
  5135. if hasLimit {
  5136. if limit < len(result.Rows) {
  5137. result.Rows = result.Rows[:limit]
  5138. }
  5139. result.RowCount = len(result.Rows)
  5140. }
  5141. }
  5142. // resultRowToStorageRow converts a Result row back to storage.Row for expression evaluation.
  5143. func (e *Executor) resultRowToStorageRow(result *Result, rowIdx int) storage.Row {
  5144. row := make(storage.Row)
  5145. for colIdx, colName := range result.Columns {
  5146. if colIdx < len(result.Rows[rowIdx]) {
  5147. row[colName] = result.Rows[rowIdx][colIdx]
  5148. }
  5149. }
  5150. return row
  5151. }
  5152. func (e *Executor) evalIntExpr(expr parser.Expr) int {
  5153. val, _ := e.evalExpr(expr, nil)
  5154. return int(toFloat(val))
  5155. }
  5156. // Type conversion helpers
  5157. func isIntVal(v interface{}) bool {
  5158. switch v.(type) {
  5159. case int64, int, bool:
  5160. return true
  5161. default:
  5162. return false
  5163. }
  5164. }
  5165. func toInt64(v interface{}) int64 {
  5166. switch val := v.(type) {
  5167. case int64:
  5168. return val
  5169. case int:
  5170. return int64(val)
  5171. case float64:
  5172. return int64(val)
  5173. case bool:
  5174. if val {
  5175. return 1
  5176. }
  5177. return 0
  5178. default:
  5179. return 0
  5180. }
  5181. }
  5182. func toFloat(v interface{}) float64 {
  5183. switch val := v.(type) {
  5184. case nil:
  5185. return 0
  5186. case int64:
  5187. return float64(val)
  5188. case int:
  5189. return float64(val)
  5190. case float64:
  5191. return val
  5192. case bool:
  5193. if val {
  5194. return 1
  5195. }
  5196. return 0
  5197. case string:
  5198. f, _ := strconv.ParseFloat(val, 64)
  5199. return f
  5200. default:
  5201. return 0
  5202. }
  5203. }
  5204. func toBool(v interface{}) bool {
  5205. switch val := v.(type) {
  5206. case nil:
  5207. return false
  5208. case bool:
  5209. return val
  5210. case int64:
  5211. return val != 0
  5212. case int:
  5213. return val != 0
  5214. case float64:
  5215. return val != 0
  5216. case string:
  5217. return val != "" && val != "0" && strings.ToLower(val) != "false"
  5218. default:
  5219. return false
  5220. }
  5221. }
  5222. func toString(v interface{}) string {
  5223. if v == nil {
  5224. return ""
  5225. }
  5226. return fmt.Sprintf("%v", v)
  5227. }
  5228. func compare(a, b interface{}) int {
  5229. if a == nil && b == nil {
  5230. return 0
  5231. }
  5232. if a == nil {
  5233. return -1
  5234. }
  5235. if b == nil {
  5236. return 1
  5237. }
  5238. // Try numeric comparison
  5239. fa, oka := toNumeric(a)
  5240. fb, okb := toNumeric(b)
  5241. if oka && okb {
  5242. if fa < fb {
  5243. return -1
  5244. }
  5245. if fa > fb {
  5246. return 1
  5247. }
  5248. return 0
  5249. }
  5250. // String comparison
  5251. sa := toString(a)
  5252. sb := toString(b)
  5253. return strings.Compare(sa, sb)
  5254. }
  5255. func toNumeric(v interface{}) (float64, bool) {
  5256. switch val := v.(type) {
  5257. case int64:
  5258. return float64(val), true
  5259. case int:
  5260. return float64(val), true
  5261. case float64:
  5262. return val, true
  5263. case string:
  5264. f, err := strconv.ParseFloat(val, 64)
  5265. return f, err == nil
  5266. default:
  5267. return 0, false
  5268. }
  5269. }
  5270. // splitANDClauses flattens a tree of AND binary expressions into a slice of leaf conditions.
  5271. func splitANDClauses(expr parser.Expr) []parser.Expr {
  5272. if bin, ok := expr.(*parser.BinaryExpr); ok && bin.Op == lexer.TokenAND {
  5273. left := splitANDClauses(bin.Left)
  5274. right := splitANDClauses(bin.Right)
  5275. return append(left, right...)
  5276. }
  5277. return []parser.Expr{expr}
  5278. }
  5279. // collectColumnRefs returns all unqualified column names referenced in an expression.
  5280. func collectColumnRefs(expr parser.Expr) []string {
  5281. var refs []string
  5282. var hasSubquery bool
  5283. var walk func(parser.Expr)
  5284. walk = func(e parser.Expr) {
  5285. if e == nil {
  5286. return
  5287. }
  5288. switch n := e.(type) {
  5289. case *parser.ColumnRef:
  5290. refs = append(refs, n.Column)
  5291. case *parser.BinaryExpr:
  5292. walk(n.Left)
  5293. walk(n.Right)
  5294. case *parser.UnaryExpr:
  5295. walk(n.Operand)
  5296. case *parser.InExpr:
  5297. walk(n.Left)
  5298. // Check for subquery
  5299. if n.Subquery != nil {
  5300. hasSubquery = true
  5301. }
  5302. for _, v := range n.Values {
  5303. walk(v)
  5304. }
  5305. case *parser.BetweenExpr:
  5306. walk(n.Left)
  5307. walk(n.Low)
  5308. walk(n.High)
  5309. case *parser.LikeExpr:
  5310. walk(n.Left)
  5311. walk(n.Pattern)
  5312. case *parser.IsNullExpr:
  5313. walk(n.Left)
  5314. case *parser.CaseExpr:
  5315. walk(n.Operand)
  5316. for _, w := range n.Whens {
  5317. walk(w.Condition)
  5318. walk(w.Result)
  5319. }
  5320. walk(n.Else)
  5321. case *parser.FunctionCall:
  5322. for _, a := range n.Args {
  5323. walk(a)
  5324. }
  5325. case *parser.ParenExpr:
  5326. walk(n.Expr)
  5327. case *parser.CastExpr:
  5328. walk(n.Expr)
  5329. case *parser.SubqueryExpr:
  5330. // Subqueries may reference outer columns
  5331. hasSubquery = true
  5332. case *parser.ExistsExpr:
  5333. // EXISTS subqueries may reference outer columns
  5334. hasSubquery = true
  5335. case *parser.LiteralExpr:
  5336. // Literals have no column refs
  5337. }
  5338. }
  5339. walk(expr)
  5340. // If we have subqueries, add a sentinel value to indicate non-constant
  5341. if hasSubquery {
  5342. refs = append(refs, "__subquery__")
  5343. }
  5344. return refs
  5345. }
  5346. type tableColRef struct{ tbl, col string }
  5347. // collectTableColumnRefs returns all column references with their table qualifier (may be "").
  5348. func collectTableColumnRefs(expr parser.Expr) []tableColRef {
  5349. var refs []tableColRef
  5350. var walk func(parser.Expr)
  5351. walk = func(e parser.Expr) {
  5352. if e == nil {
  5353. return
  5354. }
  5355. switch n := e.(type) {
  5356. case *parser.ColumnRef:
  5357. refs = append(refs, tableColRef{tbl: n.Table, col: n.Column})
  5358. case *parser.BinaryExpr:
  5359. walk(n.Left)
  5360. walk(n.Right)
  5361. case *parser.UnaryExpr:
  5362. walk(n.Operand)
  5363. case *parser.InExpr:
  5364. walk(n.Left)
  5365. for _, v := range n.Values {
  5366. walk(v)
  5367. }
  5368. case *parser.BetweenExpr:
  5369. walk(n.Left)
  5370. walk(n.Low)
  5371. walk(n.High)
  5372. case *parser.LikeExpr:
  5373. walk(n.Left)
  5374. walk(n.Pattern)
  5375. case *parser.IsNullExpr:
  5376. walk(n.Left)
  5377. case *parser.CaseExpr:
  5378. walk(n.Operand)
  5379. for _, w := range n.Whens {
  5380. walk(w.Condition)
  5381. walk(w.Result)
  5382. }
  5383. walk(n.Else)
  5384. case *parser.FunctionCall:
  5385. for _, a := range n.Args {
  5386. walk(a)
  5387. }
  5388. }
  5389. }
  5390. walk(expr)
  5391. return refs
  5392. }
  5393. // combineAND combines a list of expressions with AND.
  5394. func combineAND(clauses []parser.Expr) parser.Expr {
  5395. if len(clauses) == 0 {
  5396. return nil
  5397. }
  5398. result := clauses[0]
  5399. for _, c := range clauses[1:] {
  5400. result = &parser.BinaryExpr{Left: result, Op: lexer.TokenAND, Right: c}
  5401. }
  5402. return result
  5403. }
  5404. // matchLike matches a string against a SQL LIKE pattern.
  5405. func matchLike(s, pattern string) bool {
  5406. // Simple implementation - convert to lowercase for case-insensitive matching
  5407. s = strings.ToLower(s)
  5408. pattern = strings.ToLower(pattern)
  5409. return matchLikeHelper(s, pattern)
  5410. }
  5411. func matchLikeHelper(s, p string) bool {
  5412. if p == "" {
  5413. return s == ""
  5414. }
  5415. if p[0] == '%' {
  5416. // % matches any sequence
  5417. for i := 0; i <= len(s); i++ {
  5418. if matchLikeHelper(s[i:], p[1:]) {
  5419. return true
  5420. }
  5421. }
  5422. return false
  5423. }
  5424. if s == "" {
  5425. return false
  5426. }
  5427. if p[0] == '_' || p[0] == s[0] {
  5428. return matchLikeHelper(s[1:], p[1:])
  5429. }
  5430. return false
  5431. }
  5432. // matchGlob matches a string against a GLOB pattern.
  5433. // GLOB uses * for any sequence and ? for single character (case-sensitive).
  5434. func matchGlob(pattern, s string) bool {
  5435. return matchGlobHelper(pattern, s)
  5436. }
  5437. func matchGlobHelper(p, s string) bool {
  5438. if p == "" {
  5439. return s == ""
  5440. }
  5441. if p[0] == '*' {
  5442. // * matches any sequence
  5443. for i := 0; i <= len(s); i++ {
  5444. if matchGlobHelper(p[1:], s[i:]) {
  5445. return true
  5446. }
  5447. }
  5448. return false
  5449. }
  5450. if s == "" {
  5451. return false
  5452. }
  5453. if p[0] == '?' || p[0] == s[0] {
  5454. return matchGlobHelper(p[1:], s[1:])
  5455. }
  5456. // Handle character classes [...]
  5457. if p[0] == '[' {
  5458. end := strings.Index(p, "]")
  5459. if end > 0 {
  5460. class := p[1:end]
  5461. match := false
  5462. negate := false
  5463. if len(class) > 0 && class[0] == '^' {
  5464. negate = true
  5465. class = class[1:]
  5466. }
  5467. for _, c := range class {
  5468. if byte(c) == s[0] {
  5469. match = true
  5470. break
  5471. }
  5472. }
  5473. if negate {
  5474. match = !match
  5475. }
  5476. if match {
  5477. return matchGlobHelper(p[end+1:], s[1:])
  5478. }
  5479. }
  5480. }
  5481. return false
  5482. }
  5483. // applyDistinct removes duplicate rows from the result
  5484. func (e *Executor) applyDistinct(rows [][]interface{}) [][]interface{} {
  5485. if len(rows) == 0 {
  5486. return rows
  5487. }
  5488. seen := make(map[string]bool)
  5489. uniqueRows := make([][]interface{}, 0)
  5490. for _, row := range rows {
  5491. // Create a key from all column values
  5492. key := ""
  5493. for i, val := range row {
  5494. if i > 0 {
  5495. key += "\x00" // Use null byte as separator
  5496. }
  5497. key += fmt.Sprintf("%v", val)
  5498. }
  5499. if !seen[key] {
  5500. seen[key] = true
  5501. uniqueRows = append(uniqueRows, row)
  5502. }
  5503. }
  5504. return uniqueRows
  5505. }