executor.go 135 KB

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