2
0

executor.go 131 KB

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