2
0

executor.go 143 KB

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