2
0

executor.go 141 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. // Then, truncate all data rows
  2298. e.table.Truncate(tableRef.Name)
  2299. // Finally, drop the table schema
  2300. if err := e.schema.DropTable(tableRef.Name); err != nil {
  2301. return nil, err
  2302. }
  2303. }
  2304. if err := e.SyncCatalog(); err != nil {
  2305. return nil, err
  2306. }
  2307. result := NewResult("DROP TABLE")
  2308. return result, nil
  2309. }
  2310. // executeCreateIndex creates a new index.
  2311. func (e *Executor) executeCreateIndex(stmt *parser.CreateIndexStmt) (*Result, error) {
  2312. // Check if index already exists
  2313. if e.schema.IndexExists(stmt.Name) {
  2314. if stmt.IfNotExists {
  2315. result := NewResult("CREATE INDEX")
  2316. return result, nil
  2317. }
  2318. return nil, fmt.Errorf("index already exists: %s", stmt.Name)
  2319. }
  2320. // Verify table exists
  2321. if !e.schema.TableExists(stmt.Table) {
  2322. return nil, fmt.Errorf("table not found: %s", stmt.Table)
  2323. }
  2324. // Verify columns exist
  2325. schema, err := e.schema.GetSchema(stmt.Table)
  2326. if err != nil {
  2327. return nil, err
  2328. }
  2329. for _, col := range stmt.Columns {
  2330. if _, found := schema.GetColumn(col.Name); !found {
  2331. return nil, fmt.Errorf("column not found: %s", col.Name)
  2332. }
  2333. }
  2334. // Create storage index
  2335. index := &storage.Index{
  2336. Name: stmt.Name,
  2337. Table: stmt.Table,
  2338. Unique: stmt.Unique,
  2339. }
  2340. for _, col := range stmt.Columns {
  2341. index.Columns = append(index.Columns, storage.IndexColumn{
  2342. Name: col.Name,
  2343. Desc: col.Desc,
  2344. })
  2345. }
  2346. if err := e.schema.CreateIndex(index); err != nil {
  2347. if stmt.IfNotExists && strings.Contains(err.Error(), "index already exists") {
  2348. return NewResult("CREATE INDEX"), nil
  2349. }
  2350. return nil, err
  2351. }
  2352. // Build index entries for existing rows
  2353. columns := make([]string, len(stmt.Columns))
  2354. for i, col := range stmt.Columns {
  2355. columns[i] = col.Name
  2356. }
  2357. if err := e.table.BuildIndex(stmt.Name, stmt.Table, columns); err != nil {
  2358. // Rollback index creation on failure
  2359. e.schema.DropIndex(stmt.Name)
  2360. return nil, fmt.Errorf("failed to build index: %w", err)
  2361. }
  2362. result := NewResult("CREATE INDEX")
  2363. return result, nil
  2364. }
  2365. // executeDropIndex drops an index.
  2366. func (e *Executor) executeDropIndex(stmt *parser.DropIndexStmt) (*Result, error) {
  2367. if !e.schema.IndexExists(stmt.Name) {
  2368. if stmt.IfExists {
  2369. result := NewResult("DROP INDEX")
  2370. return result, nil
  2371. }
  2372. return nil, fmt.Errorf("index not found: %s", stmt.Name)
  2373. }
  2374. // Get index info to clear entries
  2375. index, err := e.schema.GetIndex(stmt.Name)
  2376. if err == nil && index != nil {
  2377. columns := make([]string, len(index.Columns))
  2378. for i, col := range index.Columns {
  2379. columns[i] = col.Name
  2380. }
  2381. e.table.ClearIndex(stmt.Name, index.Table, columns)
  2382. }
  2383. if err := e.schema.DropIndex(stmt.Name); err != nil {
  2384. return nil, err
  2385. }
  2386. result := NewResult("DROP INDEX")
  2387. return result, nil
  2388. }
  2389. func (e *Executor) executeCreateView(stmt *parser.CreateViewStmt) (*Result, error) {
  2390. name := strings.ToLower(stmt.View.Name)
  2391. if _, exists := e.views[name]; exists {
  2392. if stmt.IfNotExists {
  2393. return NewResult("CREATE VIEW"), nil
  2394. }
  2395. return nil, fmt.Errorf("view already exists: %s", stmt.View.Name)
  2396. }
  2397. e.views[name] = stmt.Select
  2398. // Derive view columns from SELECT list for catalog registration.
  2399. var viewCols []analyzer.ColumnInfo
  2400. hasStar := false
  2401. for _, col := range stmt.Select.Columns {
  2402. if col.Star {
  2403. hasStar = true
  2404. break
  2405. }
  2406. colName := col.Alias
  2407. if colName == "" {
  2408. if ref, ok := col.Expr.(*parser.ColumnRef); ok {
  2409. colName = ref.Column
  2410. } else {
  2411. colName = fmt.Sprintf("col_%d", len(viewCols))
  2412. }
  2413. }
  2414. viewCols = append(viewCols, analyzer.ColumnInfo{
  2415. Name: colName,
  2416. TableName: stmt.View.Name,
  2417. Type: analyzer.TypeAny,
  2418. Nullable: true,
  2419. })
  2420. }
  2421. // For SELECT *, pull columns from the underlying table(s).
  2422. if hasStar && len(stmt.Select.From) > 0 {
  2423. baseName := stmt.Select.From[0].Name
  2424. if schema, err := e.schema.GetSchema(baseName); err == nil {
  2425. for _, c := range schema.Columns {
  2426. viewCols = append(viewCols, analyzer.ColumnInfo{
  2427. Name: c.Name,
  2428. TableName: stmt.View.Name,
  2429. Type: analyzer.TypeAny,
  2430. Nullable: true,
  2431. })
  2432. }
  2433. }
  2434. }
  2435. // Register in catalog so the analyzer accepts SELECT FROM this view.
  2436. e.catalog.CreateTable(&analyzer.TableInfo{ //nolint:errcheck
  2437. Name: stmt.View.Name,
  2438. Columns: viewCols,
  2439. IsView: true,
  2440. })
  2441. return NewResult("CREATE VIEW"), nil
  2442. }
  2443. func (e *Executor) executeDropView(stmt *parser.DropViewStmt) (*Result, error) {
  2444. for _, ref := range stmt.Views {
  2445. name := strings.ToLower(ref.Name)
  2446. if _, exists := e.views[name]; !exists {
  2447. if stmt.IfExists {
  2448. continue
  2449. }
  2450. return nil, fmt.Errorf("view not found: %s", ref.Name)
  2451. }
  2452. delete(e.views, name)
  2453. e.catalog.DropTable(ref.Name) //nolint:errcheck
  2454. }
  2455. return NewResult("DROP VIEW"), nil
  2456. }
  2457. // executeAlterTable executes an ALTER TABLE statement.
  2458. func (e *Executor) executeAlterTable(stmt *parser.AlterTableStmt) (*Result, error) {
  2459. switch action := stmt.Action.(type) {
  2460. case *parser.AddColumnAction:
  2461. return e.executeAlterTableAddColumn(stmt.Table, action)
  2462. case *parser.DropColumnAction:
  2463. return e.executeAlterTableDropColumn(stmt.Table, action)
  2464. case *parser.RenameTableAction:
  2465. return e.executeAlterTableRename(stmt.Table, action)
  2466. case *parser.RenameColumnAction:
  2467. return e.executeAlterTableRenameColumn(stmt.Table, action)
  2468. default:
  2469. return nil, fmt.Errorf("unsupported ALTER TABLE action: %T", action)
  2470. }
  2471. }
  2472. // executeAlterTableAddColumn adds a column to a table.
  2473. func (e *Executor) executeAlterTableAddColumn(table string, action *parser.AddColumnAction) (*Result, error) {
  2474. if action.IfNotExists {
  2475. schema, err := e.schema.GetSchema(table)
  2476. if err != nil {
  2477. return nil, err
  2478. }
  2479. if _, exists := schema.GetColumn(action.Column.Name); exists {
  2480. return NewResult("ALTER TABLE"), nil
  2481. }
  2482. }
  2483. col := storage.Column{
  2484. Name: action.Column.Name,
  2485. Type: action.Column.Type.Name,
  2486. Nullable: true,
  2487. }
  2488. // Process column constraints
  2489. for _, constraint := range action.Column.Constraints {
  2490. switch constraint.Type {
  2491. case parser.ConstraintPrimaryKey:
  2492. col.PrimaryKey = true
  2493. col.Nullable = false
  2494. case parser.ConstraintNotNull:
  2495. col.Nullable = false
  2496. case parser.ConstraintDefault:
  2497. if constraint.Default != nil {
  2498. val, _ := e.evalExpr(constraint.Default, nil)
  2499. col.Default = val
  2500. }
  2501. }
  2502. }
  2503. if err := e.schema.AddColumn(table, col); err != nil {
  2504. if action.IfNotExists && strings.Contains(err.Error(), "column already exists") {
  2505. return NewResult("ALTER TABLE"), nil
  2506. }
  2507. return nil, err
  2508. }
  2509. // Update catalog
  2510. e.SyncCatalog()
  2511. result := NewResult("ALTER TABLE")
  2512. return result, nil
  2513. }
  2514. // executeAlterTableDropColumn drops a column from a table.
  2515. func (e *Executor) executeAlterTableDropColumn(table string, action *parser.DropColumnAction) (*Result, error) {
  2516. if err := e.schema.DropColumn(table, action.Column); err != nil {
  2517. return nil, err
  2518. }
  2519. // Update catalog
  2520. e.SyncCatalog()
  2521. result := NewResult("ALTER TABLE")
  2522. return result, nil
  2523. }
  2524. // executeAlterTableRename renames a table.
  2525. func (e *Executor) executeAlterTableRename(table string, action *parser.RenameTableAction) (*Result, error) {
  2526. if err := e.schema.RenameTable(table, action.NewName); err != nil {
  2527. return nil, err
  2528. }
  2529. // Update catalog
  2530. e.SyncCatalog()
  2531. result := NewResult("ALTER TABLE")
  2532. return result, nil
  2533. }
  2534. // executeAlterTableRenameColumn renames a column.
  2535. func (e *Executor) executeAlterTableRenameColumn(table string, action *parser.RenameColumnAction) (*Result, error) {
  2536. if err := e.schema.RenameColumn(table, action.OldName, action.NewName); err != nil {
  2537. return nil, err
  2538. }
  2539. // Update catalog
  2540. e.SyncCatalog()
  2541. result := NewResult("ALTER TABLE")
  2542. return result, nil
  2543. }
  2544. // Transaction execution methods
  2545. // executeBegin starts a new transaction.
  2546. func (e *Executor) executeBegin(stmt *parser.BeginStmt) (*Result, error) {
  2547. if e.inTransaction {
  2548. return nil, fmt.Errorf("cannot start a transaction within a transaction")
  2549. }
  2550. e.inTransaction = true
  2551. e.savepoints = nil
  2552. e.savepointPositions = nil
  2553. e.txLog = nil
  2554. e.schema.BeginTransaction()
  2555. result := NewResult("BEGIN")
  2556. return result, nil
  2557. }
  2558. // executeCommit commits the current transaction.
  2559. func (e *Executor) executeCommit(stmt *parser.CommitStmt) (*Result, error) {
  2560. if !e.inTransaction {
  2561. return nil, fmt.Errorf("cannot commit: no transaction in progress")
  2562. }
  2563. // Clear transaction state
  2564. e.inTransaction = false
  2565. e.savepoints = nil
  2566. e.savepointPositions = nil
  2567. e.txLog = nil
  2568. e.schema.EndTransaction()
  2569. result := NewResult("COMMIT")
  2570. return result, nil
  2571. }
  2572. // executeRollback rolls back the current transaction or to a savepoint.
  2573. func (e *Executor) executeRollback(stmt *parser.RollbackStmt) (*Result, error) {
  2574. if !e.inTransaction {
  2575. return nil, fmt.Errorf("cannot rollback: no transaction in progress")
  2576. }
  2577. if stmt.Savepoint != "" {
  2578. // Rollback to savepoint
  2579. return e.rollbackToSavepoint(stmt.Savepoint)
  2580. }
  2581. // Full rollback - undo all operations in reverse order
  2582. var rollbackErr error
  2583. for i := len(e.txLog) - 1; i >= 0; i-- {
  2584. entry := e.txLog[i]
  2585. if err := e.undoOperation(entry); err != nil {
  2586. if rollbackErr == nil {
  2587. rollbackErr = err
  2588. }
  2589. }
  2590. }
  2591. // Clear transaction state
  2592. e.inTransaction = false
  2593. e.savepoints = nil
  2594. e.savepointPositions = nil
  2595. e.txLog = nil
  2596. e.schema.EndTransaction()
  2597. if rollbackErr != nil {
  2598. return nil, fmt.Errorf("rollback failed: %w", rollbackErr)
  2599. }
  2600. result := NewResult("ROLLBACK")
  2601. return result, nil
  2602. }
  2603. // executeSavepoint creates a savepoint.
  2604. func (e *Executor) executeSavepoint(stmt *parser.SavepointStmt) (*Result, error) {
  2605. if !e.inTransaction {
  2606. // SQLite allows SAVEPOINT outside transaction (starts implicit transaction)
  2607. e.inTransaction = true
  2608. e.txLog = nil
  2609. e.schema.BeginTransaction()
  2610. }
  2611. // Add savepoint marker
  2612. e.savepoints = append(e.savepoints, stmt.Name)
  2613. e.savepointPositions = append(e.savepointPositions, len(e.txLog))
  2614. result := NewResult("SAVEPOINT")
  2615. return result, nil
  2616. }
  2617. // executeRelease releases a savepoint.
  2618. func (e *Executor) executeRelease(stmt *parser.ReleaseStmt) (*Result, error) {
  2619. if !e.inTransaction {
  2620. return nil, fmt.Errorf("cannot release savepoint: no transaction in progress")
  2621. }
  2622. // Find and remove the savepoint
  2623. found := false
  2624. for i := len(e.savepoints) - 1; i >= 0; i-- {
  2625. if e.savepoints[i] == stmt.Name {
  2626. e.savepoints = e.savepoints[:i]
  2627. e.savepointPositions = e.savepointPositions[:i]
  2628. found = true
  2629. break
  2630. }
  2631. }
  2632. if !found {
  2633. return nil, fmt.Errorf("no such savepoint: %s", stmt.Name)
  2634. }
  2635. result := NewResult("RELEASE")
  2636. return result, nil
  2637. }
  2638. // executeAttach attaches a database.
  2639. func (e *Executor) executeAttach(stmt *parser.AttachStmt) (*Result, error) {
  2640. // Check if alias already exists
  2641. if _, exists := e.attachedDatabases[stmt.Alias]; exists {
  2642. return nil, fmt.Errorf("database alias already exists: %s", stmt.Alias)
  2643. }
  2644. // Reserved alias check
  2645. if strings.EqualFold(stmt.Alias, "temp") || strings.EqualFold(stmt.Alias, "temporary") {
  2646. return nil, fmt.Errorf("reserved database alias: %s", stmt.Alias)
  2647. }
  2648. // Get the pool from the main schema manager
  2649. pool := e.schema.GetPool()
  2650. // Create new schema and table managers for the attached database
  2651. // In PizzaKV, each database is just a different namespace/prefix
  2652. schema := storage.NewSchemaManager(pool, stmt.FilePath)
  2653. table := storage.NewTableManager(pool, schema, stmt.FilePath)
  2654. // Register the database connection
  2655. e.attachedDatabases[stmt.Alias] = &DatabaseConnection{
  2656. Alias: stmt.Alias,
  2657. Path: stmt.FilePath,
  2658. Schema: schema,
  2659. Table: table,
  2660. }
  2661. // Sync the catalog with the attached database's tables
  2662. tables, _ := schema.ListTables()
  2663. for _, tableName := range tables {
  2664. tSchema, err := schema.GetSchema(tableName)
  2665. if err != nil {
  2666. continue
  2667. }
  2668. // Add with database prefix
  2669. tableInfo := tSchema.ToAnalyzerTableInfo()
  2670. tableInfo.Name = stmt.Alias + "." + tableInfo.Name
  2671. e.catalog.CreateTable(tableInfo)
  2672. }
  2673. result := NewResult("ATTACH")
  2674. return result, nil
  2675. }
  2676. // executeDetach detaches a database.
  2677. func (e *Executor) executeDetach(stmt *parser.DetachStmt) (*Result, error) {
  2678. // Cannot detach main database
  2679. if strings.EqualFold(stmt.Alias, "main") {
  2680. return nil, fmt.Errorf("cannot detach main database")
  2681. }
  2682. // Check if database exists
  2683. if _, exists := e.attachedDatabases[stmt.Alias]; !exists {
  2684. return nil, fmt.Errorf("no such database: %s", stmt.Alias)
  2685. }
  2686. // Remove from attached databases
  2687. delete(e.attachedDatabases, stmt.Alias)
  2688. // Note: We don't remove from catalog as that would be more complex
  2689. // In a production system, we'd need to track which tables belong to which database
  2690. result := NewResult("DETACH")
  2691. return result, nil
  2692. }
  2693. // rollbackToSavepoint rolls back to a specific savepoint.
  2694. func (e *Executor) rollbackToSavepoint(name string) (*Result, error) {
  2695. // Find savepoint index
  2696. savepointIdx := -1
  2697. for i := len(e.savepoints) - 1; i >= 0; i-- {
  2698. if e.savepoints[i] == name {
  2699. savepointIdx = i
  2700. break
  2701. }
  2702. }
  2703. if savepointIdx == -1 {
  2704. return nil, fmt.Errorf("no such savepoint: %s", name)
  2705. }
  2706. // Undo operations in reverse order
  2707. logPosition := e.savepointPositions[savepointIdx]
  2708. for i := len(e.txLog) - 1; i >= logPosition; i-- {
  2709. entry := e.txLog[i]
  2710. if err := e.undoOperation(entry); err != nil {
  2711. continue
  2712. }
  2713. }
  2714. e.txLog = e.txLog[:logPosition]
  2715. // Remove savepoints after the target
  2716. e.savepoints = e.savepoints[:savepointIdx+1]
  2717. e.savepointPositions = e.savepointPositions[:savepointIdx+1]
  2718. result := NewResult("ROLLBACK")
  2719. return result, nil
  2720. }
  2721. // RollbackActive rolls back an open transaction, such as when its client
  2722. // disconnects before sending COMMIT or ROLLBACK.
  2723. func (e *Executor) RollbackActive() error {
  2724. if !e.inTransaction {
  2725. return nil
  2726. }
  2727. _, err := e.executeRollback(&parser.RollbackStmt{})
  2728. return err
  2729. }
  2730. // undoOperation reverses a single operation.
  2731. func (e *Executor) undoOperation(entry txLogEntry) error {
  2732. switch entry.operation {
  2733. case "INSERT":
  2734. // Delete the inserted row
  2735. _, err := e.table.Delete(entry.table, func(r storage.Row) bool {
  2736. // Match by primary key stored in entry.key
  2737. pk := e.getPrimaryKey(entry.table)
  2738. if pk == "" {
  2739. return false
  2740. }
  2741. return fmt.Sprintf("%v", r[pk]) == entry.key
  2742. })
  2743. return err
  2744. case "DELETE":
  2745. // Re-insert the deleted row
  2746. if entry.oldData != nil {
  2747. return e.table.Insert(entry.table, entry.oldData)
  2748. }
  2749. case "UPDATE":
  2750. // Restore the old data
  2751. if entry.oldData != nil {
  2752. pk := e.getPrimaryKey(entry.table)
  2753. if pk != "" {
  2754. // Delete current row and insert old data
  2755. e.table.Delete(entry.table, func(r storage.Row) bool {
  2756. return fmt.Sprintf("%v", r[pk]) == entry.key
  2757. })
  2758. return e.table.Insert(entry.table, entry.oldData)
  2759. }
  2760. }
  2761. }
  2762. return nil
  2763. }
  2764. // getPrimaryKey returns the primary key column name for a table.
  2765. func (e *Executor) getPrimaryKey(tableName string) string {
  2766. schema, err := e.schema.GetSchema(tableName)
  2767. if err != nil {
  2768. return ""
  2769. }
  2770. return schema.PrimaryKey
  2771. }
  2772. // extractIndexableCondition extracts column name and value from a simple equality condition.
  2773. // Returns (column, value, true) if the expression is column = literal.
  2774. func (e *Executor) extractIndexableCondition(expr parser.Expr) (string, interface{}, bool) {
  2775. binExpr, ok := expr.(*parser.BinaryExpr)
  2776. if !ok {
  2777. return "", nil, false
  2778. }
  2779. // Only handle equality for now
  2780. if binExpr.Op != lexer.TokenEq {
  2781. return "", nil, false
  2782. }
  2783. // Check for column = literal pattern
  2784. colRef, leftIsCol := binExpr.Left.(*parser.ColumnRef)
  2785. litExpr, rightIsLit := binExpr.Right.(*parser.LiteralExpr)
  2786. if leftIsCol && rightIsLit {
  2787. val, _ := e.evalLiteral(litExpr)
  2788. return colRef.Column, val, true
  2789. }
  2790. // Check for literal = column pattern
  2791. litExpr, leftIsLit := binExpr.Left.(*parser.LiteralExpr)
  2792. colRef, rightIsCol := binExpr.Right.(*parser.ColumnRef)
  2793. if leftIsLit && rightIsCol {
  2794. val, _ := e.evalLiteral(litExpr)
  2795. return colRef.Column, val, true
  2796. }
  2797. return "", nil, false
  2798. }
  2799. // executePragma executes a PRAGMA statement.
  2800. func (e *Executor) executePragma(stmt *parser.PragmaStmt) (*Result, error) {
  2801. switch stmt.Name {
  2802. case "table_info":
  2803. return e.pragmaTableInfo(stmt.Arg)
  2804. case "table_list":
  2805. return e.pragmaTableList()
  2806. case "database_list":
  2807. return e.pragmaDatabaseList()
  2808. case "version":
  2809. return e.pragmaVersion()
  2810. default:
  2811. return nil, fmt.Errorf("unknown pragma: %s", stmt.Name)
  2812. }
  2813. }
  2814. // pragmaTableInfo returns column information for a table.
  2815. func (e *Executor) pragmaTableInfo(tableName string) (*Result, error) {
  2816. if tableName == "" {
  2817. return nil, fmt.Errorf("table_info requires a table name")
  2818. }
  2819. schema, err := e.schema.GetSchema(tableName)
  2820. if err != nil {
  2821. return nil, err
  2822. }
  2823. result := NewResult("PRAGMA")
  2824. result.AddColumn("cid")
  2825. result.AddColumn("name")
  2826. result.AddColumn("type")
  2827. result.AddColumn("notnull")
  2828. result.AddColumn("dflt_value")
  2829. result.AddColumn("pk")
  2830. for i, col := range schema.Columns {
  2831. notnull := 0
  2832. if !col.Nullable {
  2833. notnull = 1
  2834. }
  2835. pk := 0
  2836. if col.PrimaryKey {
  2837. pk = 1
  2838. }
  2839. result.AddRow(int64(i), col.Name, col.Type, int64(notnull), col.Default, int64(pk))
  2840. }
  2841. return result, nil
  2842. }
  2843. // pragmaTableList returns a list of all tables.
  2844. func (e *Executor) pragmaTableList() (*Result, error) {
  2845. tables, err := e.schema.ListTables()
  2846. if err != nil {
  2847. return nil, err
  2848. }
  2849. result := NewResult("PRAGMA")
  2850. result.AddColumn("schema")
  2851. result.AddColumn("name")
  2852. result.AddColumn("type")
  2853. for _, t := range tables {
  2854. result.AddRow("main", t, "table")
  2855. }
  2856. return result, nil
  2857. }
  2858. // pragmaDatabaseList returns a list of databases.
  2859. func (e *Executor) pragmaDatabaseList() (*Result, error) {
  2860. result := NewResult("PRAGMA")
  2861. result.AddColumn("seq")
  2862. result.AddColumn("name")
  2863. result.AddColumn("file")
  2864. // We only have one database
  2865. result.AddRow(int64(0), "main", "")
  2866. return result, nil
  2867. }
  2868. // pragmaVersion returns the PizzaSQL version.
  2869. func (e *Executor) pragmaVersion() (*Result, error) {
  2870. result := NewResult("PRAGMA")
  2871. result.AddColumn("version")
  2872. result.AddRow(version.String())
  2873. return result, nil
  2874. }
  2875. // executeExplain executes an EXPLAIN statement.
  2876. func (e *Executor) executeExplain(stmt *parser.ExplainStmt) (*Result, error) {
  2877. result := NewResult("EXPLAIN")
  2878. if stmt.QueryPlan {
  2879. // EXPLAIN QUERY PLAN format
  2880. result.AddColumn("id")
  2881. result.AddColumn("parent")
  2882. result.AddColumn("notused")
  2883. result.AddColumn("detail")
  2884. plan := e.generateQueryPlan(stmt.Statement)
  2885. for i, step := range plan {
  2886. result.AddRow(int64(i), int64(0), int64(0), step)
  2887. }
  2888. } else {
  2889. // Simple EXPLAIN format
  2890. result.AddColumn("addr")
  2891. result.AddColumn("opcode")
  2892. result.AddColumn("p1")
  2893. result.AddColumn("p2")
  2894. result.AddColumn("p3")
  2895. result.AddColumn("p4")
  2896. result.AddColumn("p5")
  2897. result.AddColumn("comment")
  2898. ops := e.generateOpcodes(stmt.Statement)
  2899. for i, op := range ops {
  2900. result.AddRow(int64(i), op, int64(0), int64(0), int64(0), "", int64(0), "")
  2901. }
  2902. }
  2903. return result, nil
  2904. }
  2905. // generateQueryPlan generates a simple query plan description.
  2906. func (e *Executor) generateQueryPlan(stmt parser.Statement) []string {
  2907. var plan []string
  2908. switch s := stmt.(type) {
  2909. case *parser.SelectStmt:
  2910. if len(s.From) > 0 {
  2911. plan = append(plan, fmt.Sprintf("SCAN TABLE %s", s.From[0].Name))
  2912. if s.Where != nil {
  2913. plan = append(plan, "FILTER")
  2914. }
  2915. if len(s.OrderBy) > 0 {
  2916. plan = append(plan, "SORT")
  2917. }
  2918. if s.Limit != nil {
  2919. plan = append(plan, "LIMIT")
  2920. }
  2921. } else {
  2922. plan = append(plan, "SCALAR EXPRESSION")
  2923. }
  2924. case *parser.InsertStmt:
  2925. plan = append(plan, fmt.Sprintf("INSERT INTO %s", s.Table.Name))
  2926. case *parser.UpdateStmt:
  2927. plan = append(plan, fmt.Sprintf("SCAN TABLE %s", s.Table.Name))
  2928. plan = append(plan, "UPDATE")
  2929. case *parser.DeleteStmt:
  2930. plan = append(plan, fmt.Sprintf("SCAN TABLE %s", s.Table.Name))
  2931. plan = append(plan, "DELETE")
  2932. default:
  2933. plan = append(plan, "EXECUTE")
  2934. }
  2935. return plan
  2936. }
  2937. // generateOpcodes generates simplified opcodes for EXPLAIN.
  2938. func (e *Executor) generateOpcodes(stmt parser.Statement) []string {
  2939. var ops []string
  2940. switch s := stmt.(type) {
  2941. case *parser.SelectStmt:
  2942. ops = append(ops, "Init")
  2943. if len(s.From) > 0 {
  2944. ops = append(ops, "OpenRead")
  2945. ops = append(ops, "Rewind")
  2946. ops = append(ops, "Column")
  2947. ops = append(ops, "ResultRow")
  2948. ops = append(ops, "Next")
  2949. ops = append(ops, "Close")
  2950. } else {
  2951. ops = append(ops, "Integer")
  2952. ops = append(ops, "ResultRow")
  2953. }
  2954. ops = append(ops, "Halt")
  2955. case *parser.InsertStmt:
  2956. ops = append(ops, "Init")
  2957. ops = append(ops, "OpenWrite")
  2958. ops = append(ops, "NewRowid")
  2959. ops = append(ops, "Insert")
  2960. ops = append(ops, "Close")
  2961. ops = append(ops, "Halt")
  2962. case *parser.UpdateStmt:
  2963. ops = append(ops, "Init")
  2964. ops = append(ops, "OpenWrite")
  2965. ops = append(ops, "Rewind")
  2966. ops = append(ops, "Column")
  2967. ops = append(ops, "Update")
  2968. ops = append(ops, "Next")
  2969. ops = append(ops, "Close")
  2970. ops = append(ops, "Halt")
  2971. case *parser.DeleteStmt:
  2972. ops = append(ops, "Init")
  2973. ops = append(ops, "OpenWrite")
  2974. ops = append(ops, "Rewind")
  2975. ops = append(ops, "Delete")
  2976. ops = append(ops, "Next")
  2977. ops = append(ops, "Close")
  2978. ops = append(ops, "Halt")
  2979. default:
  2980. ops = append(ops, "Init")
  2981. ops = append(ops, "Halt")
  2982. }
  2983. return ops
  2984. }
  2985. // evalExpr evaluates an expression.
  2986. func (e *Executor) evalExpr(expr parser.Expr, row storage.Row) (interface{}, error) {
  2987. if expr == nil {
  2988. return nil, nil
  2989. }
  2990. switch ex := expr.(type) {
  2991. case *parser.LiteralExpr:
  2992. return e.evalLiteral(ex)
  2993. case *parser.ColumnRef:
  2994. return e.evalColumnRef(ex, row)
  2995. case *parser.BinaryExpr:
  2996. return e.evalBinaryExpr(ex, row)
  2997. case *parser.UnaryExpr:
  2998. return e.evalUnaryExpr(ex, row)
  2999. case *parser.FunctionCall:
  3000. return e.evalFunctionCall(ex, row)
  3001. case *parser.ParenExpr:
  3002. return e.evalExpr(ex.Expr, row)
  3003. case *parser.CaseExpr:
  3004. return e.evalCaseExpr(ex, row)
  3005. case *parser.InExpr:
  3006. return e.evalInExpr(ex, row)
  3007. case *parser.BetweenExpr:
  3008. return e.evalBetweenExpr(ex, row)
  3009. case *parser.LikeExpr:
  3010. return e.evalLikeExpr(ex, row)
  3011. case *parser.IsNullExpr:
  3012. return e.evalIsNullExpr(ex, row)
  3013. case *parser.CastExpr:
  3014. return e.evalCastExpr(ex, row)
  3015. case *parser.SubqueryExpr:
  3016. return e.evalSubqueryExpr(ex, row)
  3017. case *parser.ExistsExpr:
  3018. return e.evalExistsExpr(ex, row)
  3019. default:
  3020. return nil, fmt.Errorf("unsupported expression type: %T", expr)
  3021. }
  3022. }
  3023. func (e *Executor) evalLiteral(lit *parser.LiteralExpr) (interface{}, error) {
  3024. switch lit.Type {
  3025. case lexer.TokenNumber:
  3026. // Check for scientific notation (e.g., 1e+06) or decimal point
  3027. if strings.Contains(lit.Value, ".") || strings.ContainsAny(lit.Value, "eE") {
  3028. f, err := strconv.ParseFloat(lit.Value, 64)
  3029. if err != nil {
  3030. return nil, err
  3031. }
  3032. // If it's a whole number (no fractional part), return as int64
  3033. if f == float64(int64(f)) {
  3034. return int64(f), nil
  3035. }
  3036. return f, nil
  3037. }
  3038. return strconv.ParseInt(lit.Value, 10, 64)
  3039. case lexer.TokenString:
  3040. return lit.Value, nil
  3041. case lexer.TokenNULL:
  3042. return nil, nil
  3043. case lexer.TokenTRUE:
  3044. return true, nil
  3045. case lexer.TokenFALSE:
  3046. return false, nil
  3047. default:
  3048. return lit.Value, nil
  3049. }
  3050. }
  3051. func (e *Executor) evalColumnRef(ref *parser.ColumnRef, row storage.Row) (interface{}, error) {
  3052. if row == nil {
  3053. return nil, fmt.Errorf("no row context for column: %s", ref.Column)
  3054. }
  3055. // Check for ROWID aliases (rowid, oid, _rowid_)
  3056. if storage.IsRowIDColumn(ref.Column) {
  3057. if val, ok := row["_rowid_"]; ok {
  3058. return val, nil
  3059. }
  3060. return nil, nil
  3061. }
  3062. // For qualified column references (table.column):
  3063. //
  3064. // Resolution order:
  3065. // 1. Exact qualified key in outer row ("t1.b" → outer)
  3066. // 2. Case-insensitive qualified in outer row
  3067. // 3. Exact qualified key in current row ("x.b" → inner alias)
  3068. // 4. Case-insensitive qualified in current row
  3069. // 5. Unqualified in outer row — only reached when qualified lookup in current
  3070. // row failed, meaning the qualifier refers to an outer table not the inner
  3071. // alias (e.g. "t1.b" in a subquery "FROM t1 AS x" resolves here).
  3072. // 6. Unqualified in current row (last resort)
  3073. if ref.Table != "" {
  3074. if e.outerRow != nil {
  3075. // Step 1-2: qualified lookup in outer row
  3076. if val, ok := e.outerRow[ref.Table+"."+ref.Column]; ok {
  3077. return val, nil
  3078. }
  3079. for k, v := range e.outerRow {
  3080. if strings.EqualFold(k, ref.Table+"."+ref.Column) {
  3081. return v, nil
  3082. }
  3083. }
  3084. }
  3085. // Step 3-4: qualified lookup in current row
  3086. if val, ok := row[ref.Table+"."+ref.Column]; ok {
  3087. return val, nil
  3088. }
  3089. for k, v := range row {
  3090. if strings.EqualFold(k, ref.Table+"."+ref.Column) {
  3091. return v, nil
  3092. }
  3093. }
  3094. // Step 5: qualified lookup failed in current row — try outer row unqualified.
  3095. // This handles correlated subqueries where the qualifier names an outer table
  3096. // (e.g. "t1.b" when the inner FROM is "t1 AS x", so current row has "x.b"
  3097. // but no "t1.b").
  3098. if e.outerRow != nil {
  3099. if val, ok := e.outerRow[ref.Column]; ok {
  3100. return val, nil
  3101. }
  3102. for k, v := range e.outerRow {
  3103. if strings.EqualFold(k, ref.Column) {
  3104. return v, nil
  3105. }
  3106. }
  3107. }
  3108. }
  3109. // Step 6: unqualified fallback in current row (handles unqualified refs and
  3110. // single-table queries like "SELECT t1.a FROM t1" where rows have plain keys).
  3111. if val, ok := row[ref.Column]; ok {
  3112. return val, nil
  3113. }
  3114. for k, v := range row {
  3115. if strings.EqualFold(k, ref.Column) {
  3116. return v, nil
  3117. }
  3118. }
  3119. // For unqualified refs with an outer row context (ref.Table == "").
  3120. if e.outerRow != nil && ref.Table == "" {
  3121. if val, ok := e.outerRow[ref.Column]; ok {
  3122. return val, nil
  3123. }
  3124. for k, v := range e.outerRow {
  3125. if strings.EqualFold(k, ref.Column) {
  3126. return v, nil
  3127. }
  3128. }
  3129. }
  3130. return nil, nil // Column not found, return NULL
  3131. }
  3132. func (e *Executor) evalBinaryExpr(expr *parser.BinaryExpr, row storage.Row) (interface{}, error) {
  3133. left, err := e.evalExpr(expr.Left, row)
  3134. if err != nil {
  3135. return nil, err
  3136. }
  3137. right, err := e.evalExpr(expr.Right, row)
  3138. if err != nil {
  3139. return nil, err
  3140. }
  3141. switch expr.Op {
  3142. case lexer.TokenPlus:
  3143. if left == nil || right == nil {
  3144. return nil, nil
  3145. }
  3146. if isIntVal(left) && isIntVal(right) {
  3147. return toInt64(left) + toInt64(right), nil
  3148. }
  3149. return toFloat(left) + toFloat(right), nil
  3150. case lexer.TokenMinus:
  3151. if left == nil || right == nil {
  3152. return nil, nil
  3153. }
  3154. if isIntVal(left) && isIntVal(right) {
  3155. return toInt64(left) - toInt64(right), nil
  3156. }
  3157. return toFloat(left) - toFloat(right), nil
  3158. case lexer.TokenStar:
  3159. if left == nil || right == nil {
  3160. return nil, nil
  3161. }
  3162. if isIntVal(left) && isIntVal(right) {
  3163. return toInt64(left) * toInt64(right), nil
  3164. }
  3165. return toFloat(left) * toFloat(right), nil
  3166. case lexer.TokenSlash:
  3167. if left == nil || right == nil {
  3168. return nil, nil
  3169. }
  3170. // Integer division when both operands are integers (truncates toward zero, matching SQLite)
  3171. if isIntVal(left) && isIntVal(right) {
  3172. ri := toInt64(right)
  3173. if ri == 0 {
  3174. return nil, nil
  3175. }
  3176. return toInt64(left) / ri, nil
  3177. }
  3178. r := toFloat(right)
  3179. if r == 0 {
  3180. return nil, nil // Division by zero returns NULL
  3181. }
  3182. return toFloat(left) / r, nil
  3183. case lexer.TokenPercent:
  3184. if left == nil || right == nil {
  3185. return nil, nil
  3186. }
  3187. if isIntVal(left) && isIntVal(right) {
  3188. ri := toInt64(right)
  3189. if ri == 0 {
  3190. return nil, nil
  3191. }
  3192. return toInt64(left) % ri, nil
  3193. }
  3194. return int64(toFloat(left)) % int64(toFloat(right)), nil
  3195. case lexer.TokenEq:
  3196. if left == nil || right == nil {
  3197. return nil, nil
  3198. }
  3199. return compare(left, right) == 0, nil
  3200. case lexer.TokenNeq:
  3201. if left == nil || right == nil {
  3202. return nil, nil
  3203. }
  3204. return compare(left, right) != 0, nil
  3205. case lexer.TokenLt:
  3206. if left == nil || right == nil {
  3207. return nil, nil
  3208. }
  3209. return compare(left, right) < 0, nil
  3210. case lexer.TokenLte:
  3211. if left == nil || right == nil {
  3212. return nil, nil
  3213. }
  3214. return compare(left, right) <= 0, nil
  3215. case lexer.TokenGt:
  3216. if left == nil || right == nil {
  3217. return nil, nil
  3218. }
  3219. return compare(left, right) > 0, nil
  3220. case lexer.TokenGte:
  3221. if left == nil || right == nil {
  3222. return nil, nil
  3223. }
  3224. return compare(left, right) >= 0, nil
  3225. case lexer.TokenAND:
  3226. // Three-value logic: FALSE AND x = FALSE; NULL AND TRUE = NULL; TRUE AND TRUE = TRUE
  3227. if left != nil && !toBool(left) {
  3228. return false, nil
  3229. }
  3230. if right != nil && !toBool(right) {
  3231. return false, nil
  3232. }
  3233. if left == nil || right == nil {
  3234. return nil, nil
  3235. }
  3236. return true, nil
  3237. case lexer.TokenOR:
  3238. // Three-value logic: TRUE OR x = TRUE; NULL OR FALSE = NULL; FALSE OR FALSE = FALSE
  3239. if left != nil && toBool(left) {
  3240. return true, nil
  3241. }
  3242. if right != nil && toBool(right) {
  3243. return true, nil
  3244. }
  3245. if left == nil || right == nil {
  3246. return nil, nil
  3247. }
  3248. return false, nil
  3249. case lexer.TokenConcat:
  3250. return toString(left) + toString(right), nil
  3251. default:
  3252. return nil, fmt.Errorf("unsupported operator: %v", expr.Op)
  3253. }
  3254. }
  3255. // applyBinaryOp applies a binary operator to two already-evaluated values.
  3256. func (e *Executor) applyBinaryOp(op lexer.TokenType, left, right interface{}) (interface{}, error) {
  3257. dummy := &parser.BinaryExpr{Op: op}
  3258. _ = dummy
  3259. switch op {
  3260. case lexer.TokenPlus:
  3261. if left == nil || right == nil {
  3262. return nil, nil
  3263. }
  3264. if isIntVal(left) && isIntVal(right) {
  3265. return toInt64(left) + toInt64(right), nil
  3266. }
  3267. return toFloat(left) + toFloat(right), nil
  3268. case lexer.TokenMinus:
  3269. if left == nil || right == nil {
  3270. return nil, nil
  3271. }
  3272. if isIntVal(left) && isIntVal(right) {
  3273. return toInt64(left) - toInt64(right), nil
  3274. }
  3275. return toFloat(left) - toFloat(right), nil
  3276. case lexer.TokenStar:
  3277. if left == nil || right == nil {
  3278. return nil, nil
  3279. }
  3280. if isIntVal(left) && isIntVal(right) {
  3281. return toInt64(left) * toInt64(right), nil
  3282. }
  3283. return toFloat(left) * toFloat(right), nil
  3284. case lexer.TokenSlash:
  3285. if left == nil || right == nil {
  3286. return nil, nil
  3287. }
  3288. if isIntVal(left) && isIntVal(right) {
  3289. ri := toInt64(right)
  3290. if ri == 0 {
  3291. return nil, nil
  3292. }
  3293. return toInt64(left) / ri, nil
  3294. }
  3295. r := toFloat(right)
  3296. if r == 0 {
  3297. return nil, nil
  3298. }
  3299. return toFloat(left) / r, nil
  3300. case lexer.TokenPercent:
  3301. if left == nil || right == nil {
  3302. return nil, nil
  3303. }
  3304. if isIntVal(left) && isIntVal(right) {
  3305. ri := toInt64(right)
  3306. if ri == 0 {
  3307. return nil, nil
  3308. }
  3309. return toInt64(left) % ri, nil
  3310. }
  3311. return int64(toFloat(left)) % int64(toFloat(right)), nil
  3312. case lexer.TokenEq:
  3313. if left == nil || right == nil {
  3314. return nil, nil
  3315. }
  3316. return compare(left, right) == 0, nil
  3317. case lexer.TokenNeq:
  3318. if left == nil || right == nil {
  3319. return nil, nil
  3320. }
  3321. return compare(left, right) != 0, nil
  3322. case lexer.TokenLt:
  3323. if left == nil || right == nil {
  3324. return nil, nil
  3325. }
  3326. return compare(left, right) < 0, nil
  3327. case lexer.TokenLte:
  3328. if left == nil || right == nil {
  3329. return nil, nil
  3330. }
  3331. return compare(left, right) <= 0, nil
  3332. case lexer.TokenGt:
  3333. if left == nil || right == nil {
  3334. return nil, nil
  3335. }
  3336. return compare(left, right) > 0, nil
  3337. case lexer.TokenGte:
  3338. if left == nil || right == nil {
  3339. return nil, nil
  3340. }
  3341. return compare(left, right) >= 0, nil
  3342. case lexer.TokenAND:
  3343. if left != nil && !toBool(left) {
  3344. return false, nil
  3345. }
  3346. if right != nil && !toBool(right) {
  3347. return false, nil
  3348. }
  3349. if left == nil || right == nil {
  3350. return nil, nil
  3351. }
  3352. return true, nil
  3353. case lexer.TokenOR:
  3354. if left != nil && toBool(left) {
  3355. return true, nil
  3356. }
  3357. if right != nil && toBool(right) {
  3358. return true, nil
  3359. }
  3360. if left == nil || right == nil {
  3361. return nil, nil
  3362. }
  3363. return false, nil
  3364. case lexer.TokenConcat:
  3365. return toString(left) + toString(right), nil
  3366. default:
  3367. return nil, fmt.Errorf("unsupported operator: %v", op)
  3368. }
  3369. }
  3370. // evalBuiltinFunction applies a named scalar function to pre-evaluated args.
  3371. func (e *Executor) evalBuiltinFunction(name string, args []interface{}) (interface{}, error) {
  3372. switch name {
  3373. case "NULLIF":
  3374. if len(args) >= 2 && compare(args[0], args[1]) == 0 {
  3375. return nil, nil
  3376. }
  3377. if len(args) > 0 {
  3378. return args[0], nil
  3379. }
  3380. case "IFNULL", "NVL":
  3381. if len(args) >= 2 {
  3382. if args[0] == nil {
  3383. return args[1], nil
  3384. }
  3385. return args[0], nil
  3386. }
  3387. case "COALESCE":
  3388. for _, a := range args {
  3389. if a != nil {
  3390. return a, nil
  3391. }
  3392. }
  3393. return nil, nil
  3394. case "ABS":
  3395. if len(args) > 0 && args[0] != nil {
  3396. if isIntVal(args[0]) {
  3397. v := toInt64(args[0])
  3398. if v < 0 {
  3399. return -v, nil
  3400. }
  3401. return v, nil
  3402. }
  3403. v := toFloat(args[0])
  3404. if v < 0 {
  3405. return -v, nil
  3406. }
  3407. return v, nil
  3408. }
  3409. case "LENGTH":
  3410. if len(args) > 0 && args[0] != nil {
  3411. return int64(len(fmt.Sprintf("%v", args[0]))), nil
  3412. }
  3413. }
  3414. // Fall back: store pre-evaluated values in row and build column refs.
  3415. row := make(storage.Row, len(args))
  3416. fn := &parser.FunctionCall{Name: name}
  3417. for i, a := range args {
  3418. key := fmt.Sprintf("__arg%d__", i)
  3419. row[key] = a
  3420. fn.Args = append(fn.Args, &parser.ColumnRef{Column: key})
  3421. }
  3422. return e.evalFunctionCall(fn, row)
  3423. }
  3424. func (e *Executor) evalUnaryExpr(expr *parser.UnaryExpr, row storage.Row) (interface{}, error) {
  3425. val, err := e.evalExpr(expr.Operand, row)
  3426. if err != nil {
  3427. return nil, err
  3428. }
  3429. switch expr.Op {
  3430. case lexer.TokenMinus:
  3431. if val == nil {
  3432. return nil, nil
  3433. }
  3434. if isIntVal(val) {
  3435. return -toInt64(val), nil
  3436. }
  3437. return -toFloat(val), nil
  3438. case lexer.TokenPlus:
  3439. if val == nil {
  3440. return nil, nil
  3441. }
  3442. if isIntVal(val) {
  3443. return toInt64(val), nil
  3444. }
  3445. return toFloat(val), nil
  3446. case lexer.TokenNOT:
  3447. if val == nil {
  3448. return nil, nil // NOT NULL = NULL
  3449. }
  3450. return !toBool(val), nil
  3451. default:
  3452. return val, nil
  3453. }
  3454. }
  3455. func (e *Executor) evalFunctionCall(fn *parser.FunctionCall, row storage.Row) (interface{}, error) {
  3456. name := strings.ToUpper(fn.Name)
  3457. // Evaluate arguments
  3458. args := make([]interface{}, len(fn.Args))
  3459. for i, arg := range fn.Args {
  3460. val, err := e.evalExpr(arg, row)
  3461. if err != nil {
  3462. return nil, err
  3463. }
  3464. args[i] = val
  3465. }
  3466. switch name {
  3467. case "UPPER":
  3468. if len(args) > 0 {
  3469. if args[0] == nil {
  3470. return nil, nil // NULL propagation
  3471. }
  3472. return strings.ToUpper(toString(args[0])), nil
  3473. }
  3474. case "LOWER":
  3475. if len(args) > 0 {
  3476. if args[0] == nil {
  3477. return nil, nil // NULL propagation
  3478. }
  3479. return strings.ToLower(toString(args[0])), nil
  3480. }
  3481. case "LENGTH":
  3482. if len(args) > 0 {
  3483. if args[0] == nil {
  3484. return nil, nil // NULL propagation
  3485. }
  3486. return int64(len(toString(args[0]))), nil
  3487. }
  3488. case "ABS":
  3489. if len(args) > 0 {
  3490. if args[0] == nil {
  3491. return nil, nil
  3492. }
  3493. v := toFloat(args[0])
  3494. if v < 0 {
  3495. return -v, nil
  3496. }
  3497. return v, nil
  3498. }
  3499. case "COALESCE":
  3500. for _, arg := range args {
  3501. if arg != nil {
  3502. return arg, nil
  3503. }
  3504. }
  3505. return nil, nil
  3506. case "NULLIF":
  3507. if len(args) >= 2 && compare(args[0], args[1]) == 0 {
  3508. return nil, nil
  3509. }
  3510. if len(args) > 0 {
  3511. return args[0], nil
  3512. }
  3513. case "IFNULL":
  3514. if len(args) >= 2 {
  3515. if args[0] == nil {
  3516. return args[1], nil
  3517. }
  3518. return args[0], nil
  3519. }
  3520. case "TYPEOF":
  3521. if len(args) > 0 {
  3522. switch args[0].(type) {
  3523. case nil:
  3524. return "null", nil
  3525. case int64, int:
  3526. return "integer", nil
  3527. case float64:
  3528. return "real", nil
  3529. case string:
  3530. return "text", nil
  3531. case []byte:
  3532. return "blob", nil
  3533. default:
  3534. return "text", nil
  3535. }
  3536. }
  3537. case "SUBSTR", "SUBSTRING":
  3538. if len(args) >= 2 {
  3539. s := toString(args[0])
  3540. start := int(toFloat(args[1])) - 1 // SQL is 1-indexed
  3541. if start < 0 {
  3542. start = 0
  3543. }
  3544. if start >= len(s) {
  3545. return "", nil
  3546. }
  3547. if len(args) >= 3 {
  3548. length := int(toFloat(args[2]))
  3549. if start+length > len(s) {
  3550. length = len(s) - start
  3551. }
  3552. return s[start : start+length], nil
  3553. }
  3554. return s[start:], nil
  3555. }
  3556. case "TRIM":
  3557. if len(args) > 0 {
  3558. return strings.TrimSpace(toString(args[0])), nil
  3559. }
  3560. case "REPLACE":
  3561. if len(args) >= 3 {
  3562. return strings.ReplaceAll(toString(args[0]), toString(args[1]), toString(args[2])), nil
  3563. }
  3564. // Additional SQLite functions
  3565. case "PRINTF":
  3566. if len(args) > 0 {
  3567. format := toString(args[0])
  3568. fmtArgs := make([]interface{}, len(args)-1)
  3569. for i := 1; i < len(args); i++ {
  3570. fmtArgs[i-1] = args[i]
  3571. }
  3572. return fmt.Sprintf(format, fmtArgs...), nil
  3573. }
  3574. case "HEX":
  3575. if len(args) > 0 {
  3576. s := toString(args[0])
  3577. return strings.ToUpper(fmt.Sprintf("%x", []byte(s))), nil
  3578. }
  3579. case "UNHEX":
  3580. if len(args) > 0 {
  3581. s := toString(args[0])
  3582. var result []byte
  3583. for i := 0; i < len(s)-1; i += 2 {
  3584. var b byte
  3585. fmt.Sscanf(s[i:i+2], "%x", &b)
  3586. result = append(result, b)
  3587. }
  3588. return string(result), nil
  3589. }
  3590. case "RANDOM":
  3591. return rand.Int63(), nil
  3592. case "RANDOMBLOB":
  3593. if len(args) > 0 {
  3594. n := int(toFloat(args[0]))
  3595. if n <= 0 {
  3596. n = 1
  3597. }
  3598. if n > 1000000 {
  3599. n = 1000000
  3600. }
  3601. blob := make([]byte, n)
  3602. rand.Read(blob)
  3603. return string(blob), nil
  3604. }
  3605. case "ZEROBLOB":
  3606. if len(args) > 0 {
  3607. n := int(toFloat(args[0]))
  3608. if n <= 0 {
  3609. n = 1
  3610. }
  3611. if n > 1000000 {
  3612. n = 1000000
  3613. }
  3614. return string(make([]byte, n)), nil
  3615. }
  3616. case "INSTR":
  3617. if len(args) >= 2 {
  3618. s := toString(args[0])
  3619. substr := toString(args[1])
  3620. idx := strings.Index(s, substr)
  3621. if idx < 0 {
  3622. return int64(0), nil
  3623. }
  3624. return int64(idx + 1), nil // SQL is 1-indexed
  3625. }
  3626. case "GLOB":
  3627. if len(args) >= 2 {
  3628. pattern := toString(args[0])
  3629. s := toString(args[1])
  3630. return matchGlob(pattern, s), nil
  3631. }
  3632. case "ROUND":
  3633. if len(args) > 0 {
  3634. v := toFloat(args[0])
  3635. decimals := 0
  3636. if len(args) >= 2 {
  3637. decimals = int(toFloat(args[1]))
  3638. }
  3639. mult := 1.0
  3640. for i := 0; i < decimals; i++ {
  3641. mult *= 10
  3642. }
  3643. return float64(int64(v*mult+0.5)) / mult, nil
  3644. }
  3645. case "MAX":
  3646. if len(args) > 0 {
  3647. max := args[0]
  3648. for _, arg := range args[1:] {
  3649. if compare(arg, max) > 0 {
  3650. max = arg
  3651. }
  3652. }
  3653. return max, nil
  3654. }
  3655. case "MIN":
  3656. if len(args) > 0 {
  3657. min := args[0]
  3658. for _, arg := range args[1:] {
  3659. if compare(arg, min) < 0 {
  3660. min = arg
  3661. }
  3662. }
  3663. return min, nil
  3664. }
  3665. case "CONCAT":
  3666. var result strings.Builder
  3667. for _, arg := range args {
  3668. result.WriteString(toString(arg))
  3669. }
  3670. return result.String(), nil
  3671. // Date/Time functions
  3672. case "DATE":
  3673. return evalDateFunc(args)
  3674. case "TIME":
  3675. return evalTimeFunc(args)
  3676. case "DATETIME":
  3677. return evalDatetimeFunc(args)
  3678. case "JULIANDAY":
  3679. return evalJuliandayFunc(args)
  3680. case "UNIXEPOCH":
  3681. return evalUnixepochFunc(args)
  3682. case "STRFTIME":
  3683. return evalStrftimeFunc(args)
  3684. case "TIMEDIFF":
  3685. return evalTimediffFunc(args)
  3686. case "PIZZASQL_VERSION", "SQLITE_VERSION":
  3687. return version.String(), nil
  3688. }
  3689. return nil, nil
  3690. }
  3691. func (e *Executor) evalCaseExpr(expr *parser.CaseExpr, row storage.Row) (interface{}, error) {
  3692. var operand interface{}
  3693. if expr.Operand != nil {
  3694. var err error
  3695. operand, err = e.evalExpr(expr.Operand, row)
  3696. if err != nil {
  3697. return nil, err
  3698. }
  3699. }
  3700. for _, when := range expr.Whens {
  3701. cond, err := e.evalExpr(when.Condition, row)
  3702. if err != nil {
  3703. return nil, err
  3704. }
  3705. var match bool
  3706. if expr.Operand != nil {
  3707. // Simple CASE: CASE operand WHEN val THEN ... — NULL operand matches nothing
  3708. if operand == nil {
  3709. continue
  3710. }
  3711. match = compare(operand, cond) == 0
  3712. } else {
  3713. // Searched CASE: CASE WHEN cond THEN ... — NULL condition is falsy
  3714. match = toBool(cond)
  3715. }
  3716. if match {
  3717. return e.evalExpr(when.Result, row)
  3718. }
  3719. }
  3720. if expr.Else != nil {
  3721. return e.evalExpr(expr.Else, row)
  3722. }
  3723. return nil, nil
  3724. }
  3725. func (e *Executor) evalInExpr(expr *parser.InExpr, row storage.Row) (interface{}, error) {
  3726. left, err := e.evalExpr(expr.Left, row)
  3727. if err != nil {
  3728. return nil, err
  3729. }
  3730. // Handle subquery: IN (SELECT ...)
  3731. if expr.Subquery != nil {
  3732. var result *Result
  3733. var err error
  3734. // Cache non-correlated subquery results for the duration of this query.
  3735. // Safe when outerRow is nil (no outer context that the subquery could reference).
  3736. if e.subqueryCache != nil && e.outerRow == nil {
  3737. if cached, ok := e.subqueryCache[expr.Subquery]; ok {
  3738. result = cached
  3739. } else {
  3740. result, err = e.executeSelect(expr.Subquery)
  3741. if err == nil {
  3742. e.subqueryCache[expr.Subquery] = result
  3743. }
  3744. }
  3745. } else {
  3746. result, err = e.executeSelect(expr.Subquery)
  3747. }
  3748. if err != nil {
  3749. return nil, fmt.Errorf("IN subquery error: %w", err)
  3750. }
  3751. if len(result.Columns) != 1 {
  3752. return nil, fmt.Errorf("subquery in IN must return exactly one column")
  3753. }
  3754. // SQL three-valued logic: if left is NULL → NULL; if any match → true; if any NULL → NULL; else false.
  3755. if left == nil {
  3756. return nil, nil
  3757. }
  3758. sawNull := false
  3759. for _, resultRow := range result.Rows {
  3760. if len(resultRow) == 0 {
  3761. continue
  3762. }
  3763. v := resultRow[0]
  3764. if v == nil {
  3765. sawNull = true
  3766. continue
  3767. }
  3768. if compare(left, v) == 0 {
  3769. if expr.Not {
  3770. return false, nil
  3771. }
  3772. return true, nil
  3773. }
  3774. }
  3775. if sawNull {
  3776. return nil, nil
  3777. }
  3778. if expr.Not {
  3779. return true, nil
  3780. }
  3781. return false, nil
  3782. }
  3783. // Handle value list: IN (1, 2, 3).
  3784. // Empty list: always FALSE (IN) / TRUE (NOT IN), even for NULL.
  3785. if len(expr.Values) == 0 {
  3786. return expr.Not, nil
  3787. }
  3788. // SQL three-valued logic: if left is NULL → NULL; if any match → true/false;
  3789. // if list contains NULL and no match → NULL.
  3790. if left == nil {
  3791. return nil, nil
  3792. }
  3793. sawNull := false
  3794. for _, val := range expr.Values {
  3795. v, err := e.evalExpr(val, row)
  3796. if err != nil {
  3797. return nil, err
  3798. }
  3799. if v == nil {
  3800. sawNull = true
  3801. continue
  3802. }
  3803. if compare(left, v) == 0 {
  3804. if expr.Not {
  3805. return false, nil
  3806. }
  3807. return true, nil
  3808. }
  3809. }
  3810. if sawNull {
  3811. return nil, nil
  3812. }
  3813. if expr.Not {
  3814. return true, nil
  3815. }
  3816. return false, nil
  3817. }
  3818. func (e *Executor) evalBetweenExpr(expr *parser.BetweenExpr, row storage.Row) (interface{}, error) {
  3819. val, err := e.evalExpr(expr.Left, row)
  3820. if err != nil {
  3821. return nil, err
  3822. }
  3823. low, err := e.evalExpr(expr.Low, row)
  3824. if err != nil {
  3825. return nil, err
  3826. }
  3827. high, err := e.evalExpr(expr.High, row)
  3828. if err != nil {
  3829. return nil, err
  3830. }
  3831. if expr.Not {
  3832. // NOT BETWEEN is equivalent to: val < low OR val > high
  3833. // We need to handle NULL using three-valued OR logic:
  3834. // NULL OR TRUE = TRUE
  3835. // NULL OR FALSE = NULL
  3836. // NULL OR NULL = NULL
  3837. var lessThan, greaterThan interface{}
  3838. if val == nil || low == nil {
  3839. lessThan = nil // NULL
  3840. } else {
  3841. lessThan = compare(val, low) < 0
  3842. }
  3843. if val == nil || high == nil {
  3844. greaterThan = nil // NULL
  3845. } else {
  3846. greaterThan = compare(val, high) > 0
  3847. }
  3848. // Implement three-valued OR
  3849. if toBool(lessThan) || toBool(greaterThan) {
  3850. return true, nil
  3851. }
  3852. if lessThan == nil || greaterThan == nil {
  3853. return nil, nil // NULL
  3854. }
  3855. return false, nil
  3856. } else {
  3857. // BETWEEN is equivalent to: val >= low AND val <= high
  3858. // Three-value logic: if val < low → FALSE (regardless of high); if val >= low and high is NULL → NULL
  3859. if val == nil {
  3860. return nil, nil
  3861. }
  3862. // x BETWEEN a AND b = (x >= a) AND (x <= b)
  3863. // NULL AND FALSE = FALSE; NULL AND TRUE = NULL
  3864. if low == nil {
  3865. // x >= NULL = NULL; check upper bound for early FALSE
  3866. if high != nil && compare(val, high) > 0 {
  3867. return false, nil // NULL AND FALSE = FALSE
  3868. }
  3869. return nil, nil // NULL AND TRUE/NULL = NULL
  3870. }
  3871. if compare(val, low) < 0 {
  3872. return false, nil // val < low → FALSE AND anything = FALSE
  3873. }
  3874. if high == nil {
  3875. return nil, nil // TRUE AND NULL = NULL
  3876. }
  3877. return compare(val, high) <= 0, nil
  3878. }
  3879. }
  3880. func (e *Executor) evalLikeExpr(expr *parser.LikeExpr, row storage.Row) (interface{}, error) {
  3881. val, err := e.evalExpr(expr.Left, row)
  3882. if err != nil {
  3883. return nil, err
  3884. }
  3885. pattern, err := e.evalExpr(expr.Pattern, row)
  3886. if err != nil {
  3887. return nil, err
  3888. }
  3889. s := toString(val)
  3890. p := toString(pattern)
  3891. // Convert SQL LIKE pattern to simple matching
  3892. // % matches any sequence, _ matches single character
  3893. matched := matchLike(s, p)
  3894. if expr.Not {
  3895. return !matched, nil
  3896. }
  3897. return matched, nil
  3898. }
  3899. func (e *Executor) evalIsNullExpr(expr *parser.IsNullExpr, row storage.Row) (interface{}, error) {
  3900. val, err := e.evalExpr(expr.Left, row)
  3901. if err != nil {
  3902. return nil, err
  3903. }
  3904. isNull := val == nil
  3905. if expr.Not {
  3906. return !isNull, nil
  3907. }
  3908. return isNull, nil
  3909. }
  3910. func (e *Executor) evalCastExpr(expr *parser.CastExpr, row storage.Row) (interface{}, error) {
  3911. val, err := e.evalExpr(expr.Expr, row)
  3912. if err != nil {
  3913. return nil, err
  3914. }
  3915. if val == nil {
  3916. return nil, nil // CAST(NULL AS any) = NULL
  3917. }
  3918. typeName := strings.ToUpper(expr.Type.Name)
  3919. switch {
  3920. case strings.Contains(typeName, "INT"):
  3921. return int64(toFloat(val)), nil
  3922. case strings.Contains(typeName, "REAL"), strings.Contains(typeName, "FLOAT"), strings.Contains(typeName, "DOUBLE"):
  3923. return toFloat(val), nil
  3924. case strings.Contains(typeName, "TEXT"), strings.Contains(typeName, "CHAR"):
  3925. return toString(val), nil
  3926. default:
  3927. return val, nil
  3928. }
  3929. }
  3930. // evalSubqueryExpr executes a scalar subquery and returns its value.
  3931. // A scalar subquery must return exactly one column. It returns:
  3932. // - The single value if the subquery returns one row
  3933. // - NULL if the subquery returns no rows
  3934. // - Error if the subquery returns more than one row (for strict SQL compliance)
  3935. func (e *Executor) evalSubqueryExpr(expr *parser.SubqueryExpr, row storage.Row) (interface{}, error) {
  3936. if row != nil && e.correlatedAggCache != nil {
  3937. if val, ok, err := e.evalDecorrelatedAggSubquery(expr.Query, row); ok || err != nil {
  3938. return val, err
  3939. }
  3940. }
  3941. // Save and set outer row context for correlated subqueries
  3942. savedOuter := e.outerRow
  3943. e.outerRow = row
  3944. defer func() { e.outerRow = savedOuter }()
  3945. // Execute the subquery
  3946. result, err := e.executeSelect(expr.Query)
  3947. if err != nil {
  3948. return nil, fmt.Errorf("subquery error: %w", err)
  3949. }
  3950. // Check for empty result
  3951. if result.RowCount == 0 {
  3952. return nil, nil // Return NULL for empty subquery
  3953. }
  3954. // Check column count
  3955. if len(result.Columns) == 0 {
  3956. return nil, fmt.Errorf("subquery must return at least one column")
  3957. }
  3958. // For scalar subquery, return first column of first row
  3959. // Note: Strict SQL would error if more than one row is returned
  3960. // but we follow SQLite behavior which just returns the first value
  3961. if len(result.Rows) > 0 && len(result.Rows[0]) > 0 {
  3962. return result.Rows[0][0], nil
  3963. }
  3964. return nil, nil
  3965. }
  3966. func (e *Executor) evalDecorrelatedAggSubquery(query *parser.SelectStmt, outerRow storage.Row) (interface{}, bool, error) {
  3967. spec, ok := e.correlatedAggSpec(query)
  3968. if !ok {
  3969. return nil, false, nil
  3970. }
  3971. outerVal, err := e.evalExpr(spec.outerKey, outerRow)
  3972. if err != nil {
  3973. return nil, true, err
  3974. }
  3975. cache, exists := e.correlatedAggCache[query]
  3976. if !exists {
  3977. cache, err = e.buildCorrelatedAggCache(query, spec)
  3978. if err != nil {
  3979. return nil, true, err
  3980. }
  3981. e.correlatedAggCache[query] = cache
  3982. }
  3983. if outerVal == nil {
  3984. return cache.defaultValue, true, nil
  3985. }
  3986. if val, exists := cache.values[fmt.Sprintf("%v", outerVal)]; exists {
  3987. return val, true, nil
  3988. }
  3989. return cache.defaultValue, true, nil
  3990. }
  3991. func (e *Executor) correlatedAggSpec(query *parser.SelectStmt) (correlatedAggSpec, bool) {
  3992. if query == nil ||
  3993. query.Compound != nil ||
  3994. len(query.Columns) != 1 ||
  3995. len(query.From) == 0 ||
  3996. query.Where == nil ||
  3997. len(query.GroupBy) > 0 ||
  3998. query.Having != nil ||
  3999. query.Limit != nil ||
  4000. query.Offset != nil {
  4001. return correlatedAggSpec{}, false
  4002. }
  4003. if query.Columns[0].Star {
  4004. return correlatedAggSpec{}, false
  4005. }
  4006. agg, ok := query.Columns[0].Expr.(*parser.FunctionCall)
  4007. if !ok {
  4008. return correlatedAggSpec{}, false
  4009. }
  4010. switch strings.ToUpper(agg.Name) {
  4011. case "COUNT", "SUM", "AVG", "MIN", "MAX":
  4012. default:
  4013. return correlatedAggSpec{}, false
  4014. }
  4015. innerAliases := collectFromAliases(query.From)
  4016. bin, ok := query.Where.(*parser.BinaryExpr)
  4017. if !ok || bin.Op != lexer.TokenEq {
  4018. return correlatedAggSpec{}, false
  4019. }
  4020. leftRef, leftIsRef := bin.Left.(*parser.ColumnRef)
  4021. rightRef, rightIsRef := bin.Right.(*parser.ColumnRef)
  4022. if !leftIsRef || !rightIsRef {
  4023. return correlatedAggSpec{}, false
  4024. }
  4025. leftInner := refBelongsToAliases(leftRef, innerAliases)
  4026. rightInner := refBelongsToAliases(rightRef, innerAliases)
  4027. if leftInner == rightInner {
  4028. return correlatedAggSpec{}, false
  4029. }
  4030. if leftInner {
  4031. return correlatedAggSpec{innerKey: leftRef, outerKey: rightRef, aggExpr: agg}, true
  4032. }
  4033. return correlatedAggSpec{innerKey: rightRef, outerKey: leftRef, aggExpr: agg}, true
  4034. }
  4035. func (e *Executor) buildCorrelatedAggCache(query *parser.SelectStmt, spec correlatedAggSpec) (*correlatedAggCache, error) {
  4036. grouped := *query
  4037. grouped.Where = nil
  4038. grouped.GroupBy = []parser.Expr{spec.innerKey}
  4039. grouped.Having = nil
  4040. grouped.OrderBy = nil
  4041. grouped.Limit = nil
  4042. grouped.Offset = nil
  4043. grouped.Columns = []parser.SelectColumn{
  4044. {Expr: spec.innerKey, Alias: "__corr_key"},
  4045. {Expr: spec.aggExpr, Alias: "__corr_value"},
  4046. }
  4047. savedOuter := e.outerRow
  4048. e.outerRow = nil
  4049. result, err := e.executeSelect(&grouped)
  4050. e.outerRow = savedOuter
  4051. if err != nil {
  4052. return nil, fmt.Errorf("decorrelated aggregate subquery error: %w", err)
  4053. }
  4054. cache := &correlatedAggCache{
  4055. values: make(map[string]interface{}, len(result.Rows)),
  4056. defaultValue: correlatedAggDefault(spec.aggExpr),
  4057. }
  4058. for _, row := range result.Rows {
  4059. if len(row) < 2 || row[0] == nil {
  4060. continue
  4061. }
  4062. cache.values[fmt.Sprintf("%v", row[0])] = row[1]
  4063. }
  4064. return cache, nil
  4065. }
  4066. func correlatedAggDefault(expr parser.Expr) interface{} {
  4067. if fn, ok := expr.(*parser.FunctionCall); ok && strings.EqualFold(fn.Name, "COUNT") {
  4068. return int64(0)
  4069. }
  4070. return nil
  4071. }
  4072. func collectFromAliases(from []parser.TableRef) map[string]struct{} {
  4073. aliases := make(map[string]struct{})
  4074. var addRef func(parser.TableRef)
  4075. addRef = func(ref parser.TableRef) {
  4076. if ref.Name != "" {
  4077. aliases[strings.ToLower(ref.Name)] = struct{}{}
  4078. }
  4079. if ref.Alias != "" {
  4080. aliases[strings.ToLower(ref.Alias)] = struct{}{}
  4081. }
  4082. if ref.Join != nil && ref.Join.Table != nil {
  4083. addRef(*ref.Join.Table)
  4084. }
  4085. }
  4086. for _, ref := range from {
  4087. addRef(ref)
  4088. }
  4089. return aliases
  4090. }
  4091. func refBelongsToAliases(ref *parser.ColumnRef, aliases map[string]struct{}) bool {
  4092. if ref == nil || ref.Table == "" {
  4093. return false
  4094. }
  4095. _, ok := aliases[strings.ToLower(ref.Table)]
  4096. return ok
  4097. }
  4098. // evalExistsExpr evaluates an EXISTS expression.
  4099. // Returns true if the subquery returns at least one row, false otherwise.
  4100. func (e *Executor) evalExistsExpr(expr *parser.ExistsExpr, row storage.Row) (interface{}, error) {
  4101. // Save and set outer row context for correlated subqueries
  4102. savedOuter := e.outerRow
  4103. e.outerRow = row
  4104. defer func() { e.outerRow = savedOuter }()
  4105. // Execute the subquery
  4106. result, err := e.executeSelect(expr.Subquery)
  4107. if err != nil {
  4108. return nil, fmt.Errorf("EXISTS subquery error: %w", err)
  4109. }
  4110. // EXISTS returns true if any rows are returned
  4111. return len(result.Rows) > 0, nil
  4112. }
  4113. // evalAggregateExpr evaluates an aggregate expression over multiple rows.
  4114. func (e *Executor) evalAggregateExpr(expr parser.Expr, rows []storage.Row) (interface{}, error) {
  4115. fn, ok := expr.(*parser.FunctionCall)
  4116. if !ok {
  4117. // Not a function call - could be a binary expression with aggregates inside
  4118. // Evaluate it with the aggregate evaluation context
  4119. return e.evalExprWithAggregates(expr, rows)
  4120. }
  4121. name := strings.ToUpper(fn.Name)
  4122. switch name {
  4123. case "COUNT":
  4124. if fn.Star {
  4125. return int64(len(rows)), nil
  4126. }
  4127. if fn.Distinct {
  4128. seen := make(map[interface{}]struct{})
  4129. for _, row := range rows {
  4130. if len(fn.Args) > 0 {
  4131. val, _ := e.evalExpr(fn.Args[0], row)
  4132. if val != nil {
  4133. seen[val] = struct{}{}
  4134. }
  4135. }
  4136. }
  4137. return int64(len(seen)), nil
  4138. }
  4139. count := int64(0)
  4140. for _, row := range rows {
  4141. if len(fn.Args) > 0 {
  4142. val, _ := e.evalExpr(fn.Args[0], row)
  4143. if val != nil {
  4144. count++
  4145. }
  4146. }
  4147. }
  4148. return count, nil
  4149. case "SUM":
  4150. var sumInt int64
  4151. var sumFloat float64
  4152. allInt := true
  4153. hasValues := false
  4154. var seen map[interface{}]struct{}
  4155. if fn.Distinct {
  4156. seen = make(map[interface{}]struct{})
  4157. }
  4158. for _, row := range rows {
  4159. if len(fn.Args) > 0 {
  4160. val, _ := e.evalExpr(fn.Args[0], row)
  4161. if val != nil {
  4162. if fn.Distinct {
  4163. key := fmt.Sprintf("%v", val)
  4164. if _, exists := seen[key]; exists {
  4165. continue
  4166. }
  4167. seen[key] = struct{}{}
  4168. }
  4169. if isIntVal(val) {
  4170. sumInt += toInt64(val)
  4171. } else {
  4172. allInt = false
  4173. sumFloat += toFloat(val)
  4174. }
  4175. hasValues = true
  4176. }
  4177. }
  4178. }
  4179. if !hasValues {
  4180. return nil, nil
  4181. }
  4182. if allInt {
  4183. return sumInt, nil
  4184. }
  4185. return sumFloat + float64(sumInt), nil
  4186. case "AVG":
  4187. var sum float64
  4188. count := 0
  4189. for _, row := range rows {
  4190. if len(fn.Args) > 0 {
  4191. val, _ := e.evalExpr(fn.Args[0], row)
  4192. if val != nil {
  4193. sum += toFloat(val)
  4194. count++
  4195. }
  4196. }
  4197. }
  4198. if count == 0 {
  4199. return nil, nil
  4200. }
  4201. return sum / float64(count), nil
  4202. case "MIN":
  4203. var min interface{}
  4204. for _, row := range rows {
  4205. if len(fn.Args) > 0 {
  4206. val, _ := e.evalExpr(fn.Args[0], row)
  4207. if val != nil && (min == nil || compare(val, min) < 0) {
  4208. min = val
  4209. }
  4210. }
  4211. }
  4212. return min, nil
  4213. case "MAX":
  4214. var max interface{}
  4215. for _, row := range rows {
  4216. if len(fn.Args) > 0 {
  4217. val, _ := e.evalExpr(fn.Args[0], row)
  4218. if val != nil && (max == nil || compare(val, max) > 0) {
  4219. max = val
  4220. }
  4221. }
  4222. }
  4223. return max, nil
  4224. default:
  4225. // Non-aggregate scalar function: evaluate args through aggregate context
  4226. // (so COUNT/MIN/etc. inside NULLIF/COALESCE work correctly).
  4227. return e.evalExprWithAggregates(expr, rows)
  4228. }
  4229. }
  4230. // evalExprWithAggregates evaluates an expression that may contain aggregate functions
  4231. func (e *Executor) evalExprWithAggregates(expr parser.Expr, rows []storage.Row) (interface{}, error) {
  4232. switch ex := expr.(type) {
  4233. case *parser.BinaryExpr:
  4234. left, err := e.evalExprWithAggregates(ex.Left, rows)
  4235. if err != nil {
  4236. return nil, err
  4237. }
  4238. right, err := e.evalExprWithAggregates(ex.Right, rows)
  4239. if err != nil {
  4240. return nil, err
  4241. }
  4242. // Use the same logic as evalBinaryExpr to preserve integer semantics.
  4243. combined := &parser.BinaryExpr{Op: ex.Op}
  4244. return e.applyBinaryOp(combined.Op, left, right)
  4245. case *parser.FunctionCall:
  4246. name := strings.ToUpper(ex.Name)
  4247. switch name {
  4248. case "COUNT", "SUM", "AVG", "MIN", "MAX", "TOTAL", "GROUP_CONCAT":
  4249. return e.evalAggregateExpr(expr, rows)
  4250. default:
  4251. // Non-aggregate: evaluate each arg with aggregate context, then apply scalar.
  4252. args := make([]interface{}, len(ex.Args))
  4253. for i, arg := range ex.Args {
  4254. v, err := e.evalExprWithAggregates(arg, rows)
  4255. if err != nil {
  4256. return nil, err
  4257. }
  4258. args[i] = v
  4259. }
  4260. return e.evalBuiltinFunction(name, args)
  4261. }
  4262. case *parser.ParenExpr:
  4263. return e.evalExprWithAggregates(ex.Expr, rows)
  4264. case *parser.UnaryExpr:
  4265. operand, err := e.evalExprWithAggregates(ex.Operand, rows)
  4266. if err != nil {
  4267. return nil, err
  4268. }
  4269. switch ex.Op {
  4270. case lexer.TokenPlus:
  4271. return operand, nil
  4272. case lexer.TokenMinus:
  4273. if operand == nil {
  4274. return nil, nil
  4275. }
  4276. if isIntVal(operand) {
  4277. return -toInt64(operand), nil
  4278. }
  4279. return -toFloat(operand), nil
  4280. case lexer.TokenNOT:
  4281. if operand == nil {
  4282. return nil, nil // NOT NULL = NULL
  4283. }
  4284. return !toBool(operand), nil
  4285. default:
  4286. return nil, fmt.Errorf("unsupported unary operator: %v", ex.Op)
  4287. }
  4288. case *parser.CastExpr:
  4289. // Evaluate inner expression with aggregate context, then apply cast.
  4290. val, err := e.evalExprWithAggregates(ex.Expr, rows)
  4291. if err != nil {
  4292. return nil, err
  4293. }
  4294. if val == nil {
  4295. return nil, nil
  4296. }
  4297. switch strings.ToUpper(ex.Type.Name) {
  4298. case "INTEGER", "INT", "BIGINT", "SMALLINT", "TINYINT", "SIGNED":
  4299. if isIntVal(val) {
  4300. return toInt64(val), nil
  4301. }
  4302. return int64(toFloat(val)), nil
  4303. case "REAL", "FLOAT", "DOUBLE", "NUMERIC", "DECIMAL":
  4304. return toFloat(val), nil
  4305. case "TEXT", "VARCHAR", "CHAR", "STRING":
  4306. return fmt.Sprintf("%v", val), nil
  4307. }
  4308. return val, nil
  4309. case *parser.CaseExpr:
  4310. var operand interface{}
  4311. if ex.Operand != nil {
  4312. operand, _ = e.evalExprWithAggregates(ex.Operand, rows)
  4313. }
  4314. for _, when := range ex.Whens {
  4315. condVal, _ := e.evalExprWithAggregates(when.Condition, rows)
  4316. var matched bool
  4317. if ex.Operand != nil {
  4318. matched = operand != nil && condVal != nil && compare(operand, condVal) == 0
  4319. } else {
  4320. matched = toBool(condVal)
  4321. }
  4322. if matched {
  4323. return e.evalExprWithAggregates(when.Result, rows)
  4324. }
  4325. }
  4326. if ex.Else != nil {
  4327. return e.evalExprWithAggregates(ex.Else, rows)
  4328. }
  4329. return nil, nil
  4330. case *parser.IsNullExpr:
  4331. val, err := e.evalExprWithAggregates(ex.Left, rows)
  4332. if err != nil {
  4333. return nil, err
  4334. }
  4335. isNull := val == nil
  4336. if ex.Not {
  4337. return !isNull, nil
  4338. }
  4339. return isNull, nil
  4340. case *parser.BetweenExpr:
  4341. val, err := e.evalExprWithAggregates(ex.Left, rows)
  4342. if err != nil {
  4343. return nil, err
  4344. }
  4345. low, err := e.evalExprWithAggregates(ex.Low, rows)
  4346. if err != nil {
  4347. return nil, err
  4348. }
  4349. high, err := e.evalExprWithAggregates(ex.High, rows)
  4350. if err != nil {
  4351. return nil, err
  4352. }
  4353. if ex.Not {
  4354. // NOT BETWEEN: val < low OR val > high
  4355. var lessThan, greaterThan interface{}
  4356. if val == nil || low == nil {
  4357. lessThan = nil
  4358. } else {
  4359. lessThan = compare(val, low) < 0
  4360. }
  4361. if val == nil || high == nil {
  4362. greaterThan = nil
  4363. } else {
  4364. greaterThan = compare(val, high) > 0
  4365. }
  4366. // Three-valued OR
  4367. if toBool(lessThan) || toBool(greaterThan) {
  4368. return true, nil
  4369. }
  4370. if lessThan == nil || greaterThan == nil {
  4371. return nil, nil
  4372. }
  4373. return false, nil
  4374. } else {
  4375. // BETWEEN: val >= low AND val <= high
  4376. if val == nil {
  4377. return nil, nil
  4378. }
  4379. if low == nil {
  4380. if high != nil && compare(val, high) > 0 {
  4381. return false, nil
  4382. }
  4383. return nil, nil
  4384. }
  4385. if compare(val, low) < 0 {
  4386. return false, nil
  4387. }
  4388. if high == nil {
  4389. return nil, nil
  4390. }
  4391. return compare(val, high) <= 0, nil
  4392. }
  4393. case *parser.InExpr:
  4394. left, err := e.evalExprWithAggregates(ex.Left, rows)
  4395. if err != nil {
  4396. return nil, err
  4397. }
  4398. // Handle subquery
  4399. if ex.Subquery != nil {
  4400. var result *Result
  4401. var err error
  4402. if e.subqueryCache != nil && e.outerRow == nil {
  4403. if cached, ok := e.subqueryCache[ex.Subquery]; ok {
  4404. result = cached
  4405. } else {
  4406. result, err = e.executeSelect(ex.Subquery)
  4407. if err == nil {
  4408. e.subqueryCache[ex.Subquery] = result
  4409. }
  4410. }
  4411. } else {
  4412. result, err = e.executeSelect(ex.Subquery)
  4413. }
  4414. if err != nil {
  4415. return nil, fmt.Errorf("IN subquery error: %w", err)
  4416. }
  4417. if len(result.Columns) != 1 {
  4418. return nil, fmt.Errorf("subquery in IN must return exactly one column")
  4419. }
  4420. if left == nil {
  4421. return nil, nil
  4422. }
  4423. sawNull := false
  4424. for _, resultRow := range result.Rows {
  4425. if len(resultRow) == 0 {
  4426. continue
  4427. }
  4428. v := resultRow[0]
  4429. if v == nil {
  4430. sawNull = true
  4431. continue
  4432. }
  4433. if compare(left, v) == 0 {
  4434. if ex.Not {
  4435. return false, nil
  4436. }
  4437. return true, nil
  4438. }
  4439. }
  4440. if sawNull {
  4441. return nil, nil
  4442. }
  4443. if ex.Not {
  4444. return true, nil
  4445. }
  4446. return false, nil
  4447. }
  4448. // Handle value list
  4449. if len(ex.Values) == 0 {
  4450. return ex.Not, nil
  4451. }
  4452. if left == nil {
  4453. return nil, nil
  4454. }
  4455. sawNull := false
  4456. for _, val := range ex.Values {
  4457. v, err := e.evalExprWithAggregates(val, rows)
  4458. if err != nil {
  4459. return nil, err
  4460. }
  4461. if v == nil {
  4462. sawNull = true
  4463. continue
  4464. }
  4465. if compare(left, v) == 0 {
  4466. if ex.Not {
  4467. return false, nil
  4468. }
  4469. return true, nil
  4470. }
  4471. }
  4472. if sawNull {
  4473. return nil, nil
  4474. }
  4475. if ex.Not {
  4476. return true, nil
  4477. }
  4478. return false, nil
  4479. default:
  4480. // Literals and non-aggregate expressions.
  4481. if len(rows) > 0 {
  4482. return e.evalExpr(expr, rows[0])
  4483. }
  4484. return e.evalExpr(expr, storage.Row{})
  4485. }
  4486. }
  4487. // Helper functions
  4488. func (e *Executor) getSelectColumns(stmt *parser.SelectStmt, schema *storage.Schema) []string {
  4489. var columns []string
  4490. for _, col := range stmt.Columns {
  4491. if col.Star {
  4492. for _, c := range schema.Columns {
  4493. columns = append(columns, c.Name)
  4494. }
  4495. } else if col.Alias != "" {
  4496. columns = append(columns, col.Alias)
  4497. } else if ref, ok := col.Expr.(*parser.ColumnRef); ok {
  4498. columns = append(columns, ref.Column)
  4499. } else {
  4500. columns = append(columns, fmt.Sprintf("column%d", len(columns)+1))
  4501. }
  4502. }
  4503. return columns
  4504. }
  4505. func (e *Executor) hasAggregates(columns []parser.SelectColumn) bool {
  4506. for _, col := range columns {
  4507. if e.isAggregate(col.Expr) {
  4508. return true
  4509. }
  4510. }
  4511. return false
  4512. }
  4513. func (e *Executor) isAggregate(expr parser.Expr) bool {
  4514. if fn, ok := expr.(*parser.FunctionCall); ok {
  4515. name := strings.ToUpper(fn.Name)
  4516. switch name {
  4517. case "COUNT", "SUM", "AVG", "MIN", "MAX", "TOTAL", "GROUP_CONCAT":
  4518. return true
  4519. }
  4520. // Non-aggregate function: check if any arg contains an aggregate.
  4521. for _, arg := range fn.Args {
  4522. if e.isAggregate(arg) {
  4523. return true
  4524. }
  4525. }
  4526. return false
  4527. }
  4528. switch ex := expr.(type) {
  4529. case *parser.UnaryExpr:
  4530. return e.isAggregate(ex.Operand)
  4531. case *parser.BinaryExpr:
  4532. return e.isAggregate(ex.Left) || e.isAggregate(ex.Right)
  4533. case *parser.ParenExpr:
  4534. return e.isAggregate(ex.Expr)
  4535. case *parser.CaseExpr:
  4536. if ex.Operand != nil && e.isAggregate(ex.Operand) {
  4537. return true
  4538. }
  4539. for _, w := range ex.Whens {
  4540. if e.isAggregate(w.Condition) || e.isAggregate(w.Result) {
  4541. return true
  4542. }
  4543. }
  4544. if ex.Else != nil {
  4545. return e.isAggregate(ex.Else)
  4546. }
  4547. case *parser.CastExpr:
  4548. return e.isAggregate(ex.Expr)
  4549. case *parser.IsNullExpr:
  4550. return e.isAggregate(ex.Left)
  4551. case *parser.BetweenExpr:
  4552. return e.isAggregate(ex.Left) || e.isAggregate(ex.Low) || e.isAggregate(ex.High)
  4553. case *parser.InExpr:
  4554. if e.isAggregate(ex.Left) {
  4555. return true
  4556. }
  4557. for _, val := range ex.Values {
  4558. if e.isAggregate(val) {
  4559. return true
  4560. }
  4561. }
  4562. return false
  4563. }
  4564. return false
  4565. }
  4566. func (e *Executor) buildGroupKey(groupBy []parser.Expr, row storage.Row) string {
  4567. var parts []string
  4568. for _, expr := range groupBy {
  4569. val, _ := e.evalExpr(expr, row)
  4570. parts = append(parts, fmt.Sprintf("%v", val))
  4571. }
  4572. return strings.Join(parts, "|")
  4573. }
  4574. // resolveOrderByPositions replaces positional ORDER BY expressions (e.g. ORDER BY 1)
  4575. // with the corresponding SELECT column expressions per SQL-92 semantics.
  4576. func resolveOrderByPositions(orderBy []parser.OrderByItem, selectCols []parser.SelectColumn) []parser.OrderByItem {
  4577. result := make([]parser.OrderByItem, len(orderBy))
  4578. for i, item := range orderBy {
  4579. if lit, ok := item.Expr.(*parser.LiteralExpr); ok {
  4580. if pos, err := strconv.Atoi(lit.Value); err == nil && pos >= 1 && pos <= len(selectCols) {
  4581. col := selectCols[pos-1]
  4582. if col.Expr != nil {
  4583. result[i] = parser.OrderByItem{Expr: col.Expr, Desc: item.Desc}
  4584. continue
  4585. }
  4586. }
  4587. }
  4588. result[i] = item
  4589. }
  4590. return result
  4591. }
  4592. // orderByLess reports whether key slice a sorts before b under orderBy.
  4593. // Keys are precomputed per-row ORDER BY expression values, one per item.
  4594. func orderByLess(a, b []interface{}, orderBy []parser.OrderByItem) bool {
  4595. for i, item := range orderBy {
  4596. cmp := compare(a[i], b[i])
  4597. if cmp != 0 {
  4598. if item.Desc {
  4599. return cmp > 0
  4600. }
  4601. return cmp < 0
  4602. }
  4603. }
  4604. return false
  4605. }
  4606. // sortKeyOrder returns a permutation of [0..len(keys)) that sorts the keys
  4607. // ascending per orderBy.
  4608. func sortKeyOrder(keys [][]interface{}, orderBy []parser.OrderByItem) []int {
  4609. order := make([]int, len(keys))
  4610. for i := range order {
  4611. order[i] = i
  4612. }
  4613. sort.Slice(order, func(a, b int) bool {
  4614. return orderByLess(keys[order[a]], keys[order[b]], orderBy)
  4615. })
  4616. return order
  4617. }
  4618. // topNHeap is a bounded max-heap that keeps the k smallest elements (per
  4619. // orderByLess) seen so far.
  4620. type topNHeap struct {
  4621. keys [][]interface{}
  4622. idx []int
  4623. orderBy []parser.OrderByItem
  4624. }
  4625. func (h *topNHeap) Len() int { return len(h.idx) }
  4626. func (h *topNHeap) Less(i, j int) bool {
  4627. return orderByLess(h.keys[h.idx[j]], h.keys[h.idx[i]], h.orderBy)
  4628. }
  4629. func (h *topNHeap) Swap(i, j int) { h.idx[i], h.idx[j] = h.idx[j], h.idx[i] }
  4630. func (h *topNHeap) Push(x interface{}) { h.idx = append(h.idx, x.(int)) }
  4631. func (h *topNHeap) Pop() interface{} {
  4632. n := len(h.idx)
  4633. x := h.idx[n-1]
  4634. h.idx = h.idx[:n-1]
  4635. return x
  4636. }
  4637. // topNKeyOrder returns the indices of the k smallest keys (per orderByLess) in
  4638. // ascending order, without fully sorting all n elements. If k >= n it falls
  4639. // back to a full sort.
  4640. func topNKeyOrder(keys [][]interface{}, orderBy []parser.OrderByItem, k int) []int {
  4641. if k <= 0 {
  4642. return nil
  4643. }
  4644. if k >= len(keys) {
  4645. return sortKeyOrder(keys, orderBy)
  4646. }
  4647. h := &topNHeap{keys: keys, orderBy: orderBy, idx: make([]int, 0, k)}
  4648. for i := range keys {
  4649. if h.Len() < k {
  4650. heap.Push(h, i)
  4651. } else if orderByLess(keys[i], keys[h.idx[0]], orderBy) {
  4652. h.idx[0] = i
  4653. heap.Fix(h, 0)
  4654. }
  4655. }
  4656. selected := append([]int(nil), h.idx...)
  4657. sort.Slice(selected, func(a, b int) bool {
  4658. return orderByLess(keys[selected[a]], keys[selected[b]], orderBy)
  4659. })
  4660. return selected
  4661. }
  4662. func reorderRows(rows []storage.Row, order []int) {
  4663. tmp := make([]storage.Row, len(rows))
  4664. for i, idx := range order {
  4665. tmp[i] = rows[idx]
  4666. }
  4667. copy(rows, tmp)
  4668. }
  4669. // sortRowKeys precomputes the ORDER BY expression value for each row so each
  4670. // expression is evaluated once per row instead of O(n log n) times.
  4671. func (e *Executor) sortRowKeys(rows []storage.Row, orderBy []parser.OrderByItem) [][]interface{} {
  4672. keys := make([][]interface{}, len(rows))
  4673. for i, row := range rows {
  4674. ks := make([]interface{}, len(orderBy))
  4675. for j, item := range orderBy {
  4676. ks[j], _ = e.evalExpr(item.Expr, row)
  4677. }
  4678. keys[i] = ks
  4679. }
  4680. return keys
  4681. }
  4682. func (e *Executor) sortRows(rows []storage.Row, orderBy []parser.OrderByItem) {
  4683. order := sortKeyOrder(e.sortRowKeys(rows, orderBy), orderBy)
  4684. reorderRows(rows, order)
  4685. }
  4686. // topNRows sorts only enough to keep the k smallest rows (per orderBy).
  4687. func (e *Executor) topNRows(rows []storage.Row, orderBy []parser.OrderByItem, k int) []storage.Row {
  4688. order := topNKeyOrder(e.sortRowKeys(rows, orderBy), orderBy, k)
  4689. out := make([]storage.Row, len(order))
  4690. for i, idx := range order {
  4691. out[i] = rows[idx]
  4692. }
  4693. return out
  4694. }
  4695. // orderAndLimitRows applies ORDER BY (with a bounded top-N selection when a
  4696. // LIMIT is present), then OFFSET and LIMIT, preserving SQL semantics.
  4697. func (e *Executor) orderAndLimitRows(rows []storage.Row, orderBy []parser.OrderByItem, limitExpr, offsetExpr parser.Expr, selectCols []parser.SelectColumn) []storage.Row {
  4698. orderBy = resolveOrderByPositions(orderBy, selectCols)
  4699. var offset, limit int
  4700. hasOffset := offsetExpr != nil
  4701. hasLimit := limitExpr != nil
  4702. if hasOffset {
  4703. offset = e.evalIntExpr(offsetExpr)
  4704. }
  4705. if hasLimit {
  4706. limit = e.evalIntExpr(limitExpr)
  4707. }
  4708. if len(orderBy) > 0 {
  4709. if hasLimit && limit >= 0 {
  4710. k := offset + limit
  4711. if k >= 0 && k < len(rows) {
  4712. rows = e.topNRows(rows, orderBy, k)
  4713. } else {
  4714. e.sortRows(rows, orderBy)
  4715. }
  4716. } else {
  4717. e.sortRows(rows, orderBy)
  4718. }
  4719. }
  4720. if hasOffset {
  4721. if offset < len(rows) {
  4722. rows = rows[offset:]
  4723. } else {
  4724. rows = nil
  4725. }
  4726. }
  4727. if hasLimit {
  4728. if limit < len(rows) {
  4729. rows = rows[:limit]
  4730. }
  4731. }
  4732. return rows
  4733. }
  4734. // resultRowKey evaluates a single ORDER BY item against a result row, honoring
  4735. // select-column aliases exactly like the previous sortResultRows implementation.
  4736. func (e *Executor) resultRowKey(result *Result, rowIdx int, item parser.OrderByItem, columnNames []string) interface{} {
  4737. if ref, ok := item.Expr.(*parser.ColumnRef); ok && ref.Table == "" {
  4738. for idx, name := range columnNames {
  4739. if strings.EqualFold(name, ref.Column) {
  4740. if idx < len(result.Rows[rowIdx]) {
  4741. return result.Rows[rowIdx][idx]
  4742. }
  4743. }
  4744. }
  4745. }
  4746. row := e.resultRowToStorageRow(result, rowIdx)
  4747. v, _ := e.evalExpr(item.Expr, row)
  4748. return v
  4749. }
  4750. // resultRowKeys precomputes the ORDER BY expression value for each result row.
  4751. func (e *Executor) resultRowKeys(result *Result, orderBy []parser.OrderByItem, columnNames []string) [][]interface{} {
  4752. keys := make([][]interface{}, len(result.Rows))
  4753. for i := range result.Rows {
  4754. ks := make([]interface{}, len(orderBy))
  4755. for j, item := range orderBy {
  4756. ks[j] = e.resultRowKey(result, i, item, columnNames)
  4757. }
  4758. keys[i] = ks
  4759. }
  4760. return keys
  4761. }
  4762. // sortResultRows sorts Result.Rows based on ORDER BY clauses.
  4763. // It handles column aliases by matching them against the select columns.
  4764. func (e *Executor) sortResultRows(result *Result, orderBy []parser.OrderByItem, selectColumns []parser.SelectColumn, columnNames []string) {
  4765. orderBy = resolveOrderByPositions(orderBy, selectColumns)
  4766. order := sortKeyOrder(e.resultRowKeys(result, orderBy, columnNames), orderBy)
  4767. rows := make([][]interface{}, len(order))
  4768. for i, idx := range order {
  4769. rows[i] = result.Rows[idx]
  4770. }
  4771. result.Rows = rows
  4772. }
  4773. // orderAndLimitResultRows applies ORDER BY (with bounded top-N selection when a
  4774. // LIMIT is present), then OFFSET and LIMIT, to a Result's rows.
  4775. func (e *Executor) orderAndLimitResultRows(result *Result, orderBy []parser.OrderByItem, limitExpr, offsetExpr parser.Expr, selectCols []parser.SelectColumn, columnNames []string) {
  4776. orderBy = resolveOrderByPositions(orderBy, selectCols)
  4777. var offset, limit int
  4778. hasOffset := offsetExpr != nil
  4779. hasLimit := limitExpr != nil
  4780. if hasOffset {
  4781. offset = e.evalIntExpr(offsetExpr)
  4782. }
  4783. if hasLimit {
  4784. limit = e.evalIntExpr(limitExpr)
  4785. }
  4786. if len(orderBy) > 0 {
  4787. if hasLimit && limit >= 0 {
  4788. k := offset + limit
  4789. if k >= 0 && k < len(result.Rows) {
  4790. order := topNKeyOrder(e.resultRowKeys(result, orderBy, columnNames), orderBy, k)
  4791. rows := make([][]interface{}, len(order))
  4792. for i, idx := range order {
  4793. rows[i] = result.Rows[idx]
  4794. }
  4795. result.Rows = rows
  4796. } else {
  4797. e.sortResultRows(result, orderBy, nil, columnNames)
  4798. }
  4799. } else {
  4800. e.sortResultRows(result, orderBy, nil, columnNames)
  4801. }
  4802. }
  4803. if hasOffset {
  4804. if offset < len(result.Rows) {
  4805. result.Rows = result.Rows[offset:]
  4806. } else {
  4807. result.Rows = nil
  4808. }
  4809. result.RowCount = len(result.Rows)
  4810. }
  4811. if hasLimit {
  4812. if limit < len(result.Rows) {
  4813. result.Rows = result.Rows[:limit]
  4814. }
  4815. result.RowCount = len(result.Rows)
  4816. }
  4817. }
  4818. // resultRowToStorageRow converts a Result row back to storage.Row for expression evaluation.
  4819. func (e *Executor) resultRowToStorageRow(result *Result, rowIdx int) storage.Row {
  4820. row := make(storage.Row)
  4821. for colIdx, colName := range result.Columns {
  4822. if colIdx < len(result.Rows[rowIdx]) {
  4823. row[colName] = result.Rows[rowIdx][colIdx]
  4824. }
  4825. }
  4826. return row
  4827. }
  4828. func (e *Executor) evalIntExpr(expr parser.Expr) int {
  4829. val, _ := e.evalExpr(expr, nil)
  4830. return int(toFloat(val))
  4831. }
  4832. // Type conversion helpers
  4833. func isIntVal(v interface{}) bool {
  4834. switch v.(type) {
  4835. case int64, int, bool:
  4836. return true
  4837. default:
  4838. return false
  4839. }
  4840. }
  4841. func toInt64(v interface{}) int64 {
  4842. switch val := v.(type) {
  4843. case int64:
  4844. return val
  4845. case int:
  4846. return int64(val)
  4847. case float64:
  4848. return int64(val)
  4849. case bool:
  4850. if val {
  4851. return 1
  4852. }
  4853. return 0
  4854. default:
  4855. return 0
  4856. }
  4857. }
  4858. func toFloat(v interface{}) float64 {
  4859. switch val := v.(type) {
  4860. case nil:
  4861. return 0
  4862. case int64:
  4863. return float64(val)
  4864. case int:
  4865. return float64(val)
  4866. case float64:
  4867. return val
  4868. case bool:
  4869. if val {
  4870. return 1
  4871. }
  4872. return 0
  4873. case string:
  4874. f, _ := strconv.ParseFloat(val, 64)
  4875. return f
  4876. default:
  4877. return 0
  4878. }
  4879. }
  4880. func toBool(v interface{}) bool {
  4881. switch val := v.(type) {
  4882. case nil:
  4883. return false
  4884. case bool:
  4885. return val
  4886. case int64:
  4887. return val != 0
  4888. case int:
  4889. return val != 0
  4890. case float64:
  4891. return val != 0
  4892. case string:
  4893. return val != "" && val != "0" && strings.ToLower(val) != "false"
  4894. default:
  4895. return false
  4896. }
  4897. }
  4898. func toString(v interface{}) string {
  4899. if v == nil {
  4900. return ""
  4901. }
  4902. return fmt.Sprintf("%v", v)
  4903. }
  4904. func compare(a, b interface{}) int {
  4905. if a == nil && b == nil {
  4906. return 0
  4907. }
  4908. if a == nil {
  4909. return -1
  4910. }
  4911. if b == nil {
  4912. return 1
  4913. }
  4914. // Try numeric comparison
  4915. fa, oka := toNumeric(a)
  4916. fb, okb := toNumeric(b)
  4917. if oka && okb {
  4918. if fa < fb {
  4919. return -1
  4920. }
  4921. if fa > fb {
  4922. return 1
  4923. }
  4924. return 0
  4925. }
  4926. // String comparison
  4927. sa := toString(a)
  4928. sb := toString(b)
  4929. return strings.Compare(sa, sb)
  4930. }
  4931. func toNumeric(v interface{}) (float64, bool) {
  4932. switch val := v.(type) {
  4933. case int64:
  4934. return float64(val), true
  4935. case int:
  4936. return float64(val), true
  4937. case float64:
  4938. return val, true
  4939. case string:
  4940. f, err := strconv.ParseFloat(val, 64)
  4941. return f, err == nil
  4942. default:
  4943. return 0, false
  4944. }
  4945. }
  4946. // splitANDClauses flattens a tree of AND binary expressions into a slice of leaf conditions.
  4947. func splitANDClauses(expr parser.Expr) []parser.Expr {
  4948. if bin, ok := expr.(*parser.BinaryExpr); ok && bin.Op == lexer.TokenAND {
  4949. left := splitANDClauses(bin.Left)
  4950. right := splitANDClauses(bin.Right)
  4951. return append(left, right...)
  4952. }
  4953. return []parser.Expr{expr}
  4954. }
  4955. // collectColumnRefs returns all unqualified column names referenced in an expression.
  4956. func collectColumnRefs(expr parser.Expr) []string {
  4957. var refs []string
  4958. var hasSubquery bool
  4959. var walk func(parser.Expr)
  4960. walk = func(e parser.Expr) {
  4961. if e == nil {
  4962. return
  4963. }
  4964. switch n := e.(type) {
  4965. case *parser.ColumnRef:
  4966. refs = append(refs, n.Column)
  4967. case *parser.BinaryExpr:
  4968. walk(n.Left)
  4969. walk(n.Right)
  4970. case *parser.UnaryExpr:
  4971. walk(n.Operand)
  4972. case *parser.InExpr:
  4973. walk(n.Left)
  4974. // Check for subquery
  4975. if n.Subquery != nil {
  4976. hasSubquery = true
  4977. }
  4978. for _, v := range n.Values {
  4979. walk(v)
  4980. }
  4981. case *parser.BetweenExpr:
  4982. walk(n.Left)
  4983. walk(n.Low)
  4984. walk(n.High)
  4985. case *parser.LikeExpr:
  4986. walk(n.Left)
  4987. walk(n.Pattern)
  4988. case *parser.IsNullExpr:
  4989. walk(n.Left)
  4990. case *parser.CaseExpr:
  4991. walk(n.Operand)
  4992. for _, w := range n.Whens {
  4993. walk(w.Condition)
  4994. walk(w.Result)
  4995. }
  4996. walk(n.Else)
  4997. case *parser.FunctionCall:
  4998. for _, a := range n.Args {
  4999. walk(a)
  5000. }
  5001. case *parser.ParenExpr:
  5002. walk(n.Expr)
  5003. case *parser.CastExpr:
  5004. walk(n.Expr)
  5005. case *parser.SubqueryExpr:
  5006. // Subqueries may reference outer columns
  5007. hasSubquery = true
  5008. case *parser.ExistsExpr:
  5009. // EXISTS subqueries may reference outer columns
  5010. hasSubquery = true
  5011. case *parser.LiteralExpr:
  5012. // Literals have no column refs
  5013. }
  5014. }
  5015. walk(expr)
  5016. // If we have subqueries, add a sentinel value to indicate non-constant
  5017. if hasSubquery {
  5018. refs = append(refs, "__subquery__")
  5019. }
  5020. return refs
  5021. }
  5022. type tableColRef struct{ tbl, col string }
  5023. // collectTableColumnRefs returns all column references with their table qualifier (may be "").
  5024. func collectTableColumnRefs(expr parser.Expr) []tableColRef {
  5025. var refs []tableColRef
  5026. var walk func(parser.Expr)
  5027. walk = func(e parser.Expr) {
  5028. if e == nil {
  5029. return
  5030. }
  5031. switch n := e.(type) {
  5032. case *parser.ColumnRef:
  5033. refs = append(refs, tableColRef{tbl: n.Table, col: n.Column})
  5034. case *parser.BinaryExpr:
  5035. walk(n.Left)
  5036. walk(n.Right)
  5037. case *parser.UnaryExpr:
  5038. walk(n.Operand)
  5039. case *parser.InExpr:
  5040. walk(n.Left)
  5041. for _, v := range n.Values {
  5042. walk(v)
  5043. }
  5044. case *parser.BetweenExpr:
  5045. walk(n.Left)
  5046. walk(n.Low)
  5047. walk(n.High)
  5048. case *parser.LikeExpr:
  5049. walk(n.Left)
  5050. walk(n.Pattern)
  5051. case *parser.IsNullExpr:
  5052. walk(n.Left)
  5053. case *parser.CaseExpr:
  5054. walk(n.Operand)
  5055. for _, w := range n.Whens {
  5056. walk(w.Condition)
  5057. walk(w.Result)
  5058. }
  5059. walk(n.Else)
  5060. case *parser.FunctionCall:
  5061. for _, a := range n.Args {
  5062. walk(a)
  5063. }
  5064. }
  5065. }
  5066. walk(expr)
  5067. return refs
  5068. }
  5069. // combineAND combines a list of expressions with AND.
  5070. func combineAND(clauses []parser.Expr) parser.Expr {
  5071. if len(clauses) == 0 {
  5072. return nil
  5073. }
  5074. result := clauses[0]
  5075. for _, c := range clauses[1:] {
  5076. result = &parser.BinaryExpr{Left: result, Op: lexer.TokenAND, Right: c}
  5077. }
  5078. return result
  5079. }
  5080. // matchLike matches a string against a SQL LIKE pattern.
  5081. func matchLike(s, pattern string) bool {
  5082. // Simple implementation - convert to lowercase for case-insensitive matching
  5083. s = strings.ToLower(s)
  5084. pattern = strings.ToLower(pattern)
  5085. return matchLikeHelper(s, pattern)
  5086. }
  5087. func matchLikeHelper(s, p string) bool {
  5088. if p == "" {
  5089. return s == ""
  5090. }
  5091. if p[0] == '%' {
  5092. // % matches any sequence
  5093. for i := 0; i <= len(s); i++ {
  5094. if matchLikeHelper(s[i:], p[1:]) {
  5095. return true
  5096. }
  5097. }
  5098. return false
  5099. }
  5100. if s == "" {
  5101. return false
  5102. }
  5103. if p[0] == '_' || p[0] == s[0] {
  5104. return matchLikeHelper(s[1:], p[1:])
  5105. }
  5106. return false
  5107. }
  5108. // matchGlob matches a string against a GLOB pattern.
  5109. // GLOB uses * for any sequence and ? for single character (case-sensitive).
  5110. func matchGlob(pattern, s string) bool {
  5111. return matchGlobHelper(pattern, s)
  5112. }
  5113. func matchGlobHelper(p, s string) bool {
  5114. if p == "" {
  5115. return s == ""
  5116. }
  5117. if p[0] == '*' {
  5118. // * matches any sequence
  5119. for i := 0; i <= len(s); i++ {
  5120. if matchGlobHelper(p[1:], s[i:]) {
  5121. return true
  5122. }
  5123. }
  5124. return false
  5125. }
  5126. if s == "" {
  5127. return false
  5128. }
  5129. if p[0] == '?' || p[0] == s[0] {
  5130. return matchGlobHelper(p[1:], s[1:])
  5131. }
  5132. // Handle character classes [...]
  5133. if p[0] == '[' {
  5134. end := strings.Index(p, "]")
  5135. if end > 0 {
  5136. class := p[1:end]
  5137. match := false
  5138. negate := false
  5139. if len(class) > 0 && class[0] == '^' {
  5140. negate = true
  5141. class = class[1:]
  5142. }
  5143. for _, c := range class {
  5144. if byte(c) == s[0] {
  5145. match = true
  5146. break
  5147. }
  5148. }
  5149. if negate {
  5150. match = !match
  5151. }
  5152. if match {
  5153. return matchGlobHelper(p[end+1:], s[1:])
  5154. }
  5155. }
  5156. }
  5157. return false
  5158. }
  5159. // applyDistinct removes duplicate rows from the result
  5160. func (e *Executor) applyDistinct(rows [][]interface{}) [][]interface{} {
  5161. if len(rows) == 0 {
  5162. return rows
  5163. }
  5164. seen := make(map[string]bool)
  5165. uniqueRows := make([][]interface{}, 0)
  5166. for _, row := range rows {
  5167. // Create a key from all column values
  5168. key := ""
  5169. for i, val := range row {
  5170. if i > 0 {
  5171. key += "\x00" // Use null byte as separator
  5172. }
  5173. key += fmt.Sprintf("%v", val)
  5174. }
  5175. if !seen[key] {
  5176. seen[key] = true
  5177. uniqueRows = append(uniqueRows, row)
  5178. }
  5179. }
  5180. return uniqueRows
  5181. }