executor.go 131 KB

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