executor.go 142 KB

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