executor.go 91 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770
  1. package executor
  2. import (
  3. "fmt"
  4. "math/rand"
  5. "sort"
  6. "strconv"
  7. "strings"
  8. "github.com/danfragoso/pizzasql-next/pkg/analyzer"
  9. "github.com/danfragoso/pizzasql-next/pkg/lexer"
  10. "github.com/danfragoso/pizzasql-next/pkg/parser"
  11. "github.com/danfragoso/pizzasql-next/pkg/storage"
  12. )
  13. // Executor executes SQL statements.
  14. type Executor struct {
  15. schema *storage.SchemaManager
  16. table *storage.TableManager
  17. analyzer *analyzer.Analyzer
  18. catalog *analyzer.Catalog
  19. // Multi-database support
  20. attachedDatabases map[string]*DatabaseConnection // alias -> connection
  21. currentDatabase string // current database alias (default is "main")
  22. // Transaction state
  23. inTransaction bool
  24. savepoints []string // stack of savepoint names
  25. txLog []txLogEntry // transaction log for rollback
  26. // Subquery context for correlated subqueries
  27. outerRow storage.Row
  28. // Per-query cache for non-correlated IN (SELECT ...) subquery results.
  29. // Keyed by subquery AST pointer; valid for one top-level Execute call.
  30. subqueryCache map[*parser.SelectStmt]*Result
  31. // In-memory view registry: view name (lowercase) → SELECT AST.
  32. views map[string]*parser.SelectStmt
  33. }
  34. // DatabaseConnection represents an attached database.
  35. type DatabaseConnection struct {
  36. Alias string
  37. Path string // Database path or identifier
  38. Schema *storage.SchemaManager
  39. Table *storage.TableManager
  40. }
  41. // txLogEntry represents a transaction log entry for rollback support.
  42. type txLogEntry struct {
  43. operation string // "INSERT", "UPDATE", "DELETE"
  44. table string
  45. key string
  46. oldData storage.Row // for UPDATE/DELETE, the original row data
  47. }
  48. // New creates a new executor.
  49. func New(schema *storage.SchemaManager, table *storage.TableManager) *Executor {
  50. catalog := analyzer.NewCatalog()
  51. executor := &Executor{
  52. schema: schema,
  53. table: table,
  54. analyzer: analyzer.New(catalog),
  55. catalog: catalog,
  56. attachedDatabases: make(map[string]*DatabaseConnection),
  57. currentDatabase: "main",
  58. views: make(map[string]*parser.SelectStmt),
  59. }
  60. // Register the main database
  61. executor.attachedDatabases["main"] = &DatabaseConnection{
  62. Alias: "main",
  63. Path: schema.GetDatabaseName(),
  64. Schema: schema,
  65. Table: table,
  66. }
  67. return executor
  68. }
  69. // SyncCatalog synchronizes the analyzer catalog with the storage schema.
  70. func (e *Executor) SyncCatalog() error {
  71. tables, err := e.schema.ListTables()
  72. if err != nil {
  73. return err
  74. }
  75. for _, tableName := range tables {
  76. schema, err := e.schema.GetSchema(tableName)
  77. if err != nil {
  78. continue
  79. }
  80. // Drop table from catalog if it exists, then recreate with updated schema
  81. e.catalog.DropTable(tableName)
  82. e.catalog.CreateTable(schema.ToAnalyzerTableInfo())
  83. }
  84. return nil
  85. }
  86. // Execute executes a SQL statement.
  87. func (e *Executor) Execute(stmt parser.Statement) (*Result, error) {
  88. e.subqueryCache = make(map[*parser.SelectStmt]*Result)
  89. defer func() { e.subqueryCache = nil }()
  90. // PRAGMA doesn't need analysis
  91. if pragma, ok := stmt.(*parser.PragmaStmt); ok {
  92. return e.executePragma(pragma)
  93. }
  94. // EXPLAIN doesn't need analysis
  95. if explain, ok := stmt.(*parser.ExplainStmt); ok {
  96. return e.executeExplain(explain)
  97. }
  98. // Transaction statements don't need analysis
  99. switch s := stmt.(type) {
  100. case *parser.BeginStmt:
  101. return e.executeBegin(s)
  102. case *parser.CommitStmt:
  103. return e.executeCommit(s)
  104. case *parser.RollbackStmt:
  105. return e.executeRollback(s)
  106. case *parser.SavepointStmt:
  107. return e.executeSavepoint(s)
  108. case *parser.ReleaseStmt:
  109. return e.executeRelease(s)
  110. case *parser.CreateIndexStmt:
  111. return e.executeCreateIndex(s)
  112. case *parser.DropIndexStmt:
  113. return e.executeDropIndex(s)
  114. case *parser.CreateViewStmt:
  115. return e.executeCreateView(s)
  116. case *parser.DropViewStmt:
  117. return e.executeDropView(s)
  118. case *parser.AttachStmt:
  119. return e.executeAttach(s)
  120. case *parser.DetachStmt:
  121. return e.executeDetach(s)
  122. }
  123. // Analyze first — create a fresh analyzer per call so concurrent requests
  124. // don't share mutable scope state (e.analyzer.scope would race otherwise).
  125. a := analyzer.New(e.catalog)
  126. if err := a.Analyze(stmt); err != nil {
  127. return nil, err
  128. }
  129. switch s := stmt.(type) {
  130. case *parser.SelectStmt:
  131. return e.executeSelect(s)
  132. case *parser.InsertStmt:
  133. return e.executeInsert(s)
  134. case *parser.UpdateStmt:
  135. return e.executeUpdate(s)
  136. case *parser.DeleteStmt:
  137. return e.executeDelete(s)
  138. case *parser.CreateTableStmt:
  139. return e.executeCreateTable(s)
  140. case *parser.DropTableStmt:
  141. return e.executeDropTable(s)
  142. case *parser.CreateIndexStmt:
  143. return e.executeCreateIndex(s)
  144. case *parser.DropIndexStmt:
  145. return e.executeDropIndex(s)
  146. case *parser.AlterTableStmt:
  147. return e.executeAlterTable(s)
  148. default:
  149. return nil, fmt.Errorf("unsupported statement type: %T", stmt)
  150. }
  151. }
  152. // executeSelect executes a SELECT statement (or compound SELECT).
  153. func (e *Executor) executeSelect(stmt *parser.SelectStmt) (*Result, error) {
  154. if stmt.Compound != nil {
  155. return e.executeCompound(stmt.Compound)
  156. }
  157. if len(stmt.From) == 0 {
  158. // SELECT without FROM (e.g., SELECT 1+1)
  159. return e.executeSelectExpr(stmt)
  160. }
  161. // Check if FROM clause is a subquery (derived table)
  162. if stmt.From[0].Subquery != nil {
  163. return e.executeSelectFromSubquery(stmt)
  164. }
  165. tableName := stmt.From[0].Name
  166. // Transparently expand view references as derived-table subqueries.
  167. if viewDef, ok := e.views[strings.ToLower(tableName)]; ok {
  168. alias := stmt.From[0].Alias
  169. if alias == "" {
  170. alias = tableName
  171. }
  172. modifiedStmt := *stmt
  173. modifiedFrom := make([]parser.TableRef, len(stmt.From))
  174. copy(modifiedFrom, stmt.From)
  175. modifiedFrom[0] = parser.TableRef{Subquery: viewDef, Alias: alias}
  176. modifiedStmt.From = modifiedFrom
  177. return e.executeSelectFromSubquery(&modifiedStmt)
  178. }
  179. schema, err := e.schema.GetSchema(tableName)
  180. if err != nil {
  181. return nil, err
  182. }
  183. // Multi-table FROM (comma-separated implicit cross join): collect and cross join all tables,
  184. // then apply WHERE after. Don't push WHERE down here — conditions reference multiple tables.
  185. isMultiTable := len(stmt.From) > 1 && stmt.From[0].Join == nil
  186. // Try to use index for WHERE clause (single-table only)
  187. var rows []storage.Row
  188. usedIndex := false
  189. if stmt.Where != nil && !isMultiTable {
  190. // Check if we can use an index
  191. colName, colValue, isEquality := e.extractIndexableCondition(stmt.Where)
  192. if isEquality {
  193. // Look for an index on this column
  194. indexes, _ := e.schema.ListTableIndexes(tableName)
  195. for _, idx := range indexes {
  196. if len(idx.Columns) == 1 && strings.EqualFold(idx.Columns[0].Name, colName) {
  197. // Use this index
  198. rows, err = e.table.SelectByIndex(tableName, idx.Name, colValue)
  199. if err == nil {
  200. usedIndex = true
  201. }
  202. break
  203. }
  204. }
  205. }
  206. }
  207. // Fall back to full table scan if no index used
  208. if !usedIndex {
  209. var filterErr error
  210. var filter func(storage.Row) bool
  211. if stmt.Where != nil && stmt.From[0].Alias == "" && !isMultiTable {
  212. filter = func(row storage.Row) bool {
  213. val, ferr := e.evalExpr(stmt.Where, row)
  214. if ferr != nil {
  215. filterErr = ferr
  216. return false
  217. }
  218. return toBool(val)
  219. }
  220. }
  221. rows, err = e.table.Select(tableName, filter)
  222. if filterErr != nil {
  223. return nil, filterErr
  224. }
  225. }
  226. if err != nil {
  227. return nil, err
  228. }
  229. // Add table alias to rows if there's an explicit alias
  230. if stmt.From[0].Alias != "" {
  231. for i := range rows {
  232. rows[i] = e.addTableAlias(rows[i], stmt.From[0].Alias)
  233. }
  234. } else if isMultiTable {
  235. // For multi-table cross joins without alias, prefix columns with table name
  236. // so WHERE can distinguish t3.a3 from t7.a7.
  237. for i := range rows {
  238. rows[i] = e.addTableAlias(rows[i], tableName)
  239. }
  240. }
  241. // Apply WHERE for single-table with alias (after alias mapping so alias.col refs work)
  242. if stmt.Where != nil && stmt.From[0].Alias != "" && !isMultiTable {
  243. var filterErr error
  244. var filtered []storage.Row
  245. for _, row := range rows {
  246. val, ferr := e.evalExpr(stmt.Where, row)
  247. if ferr != nil {
  248. filterErr = ferr
  249. break
  250. }
  251. if toBool(val) {
  252. filtered = append(filtered, row)
  253. }
  254. }
  255. if filterErr != nil {
  256. return nil, filterErr
  257. }
  258. rows = filtered
  259. }
  260. // Handle explicit JOINs
  261. if len(stmt.From) > 0 && stmt.From[0].Join != nil {
  262. rows, err = e.executeJoins(stmt.From[0], rows)
  263. if err != nil {
  264. return nil, err
  265. }
  266. }
  267. // Handle implicit cross joins (comma-separated FROM tables)
  268. if isMultiTable {
  269. // Build the column-set for each table so we can push WHERE conditions down.
  270. type tableInfo struct {
  271. alias string
  272. name string
  273. colsSet map[string]bool // lower-case column names for this table
  274. }
  275. allTableInfos := make([]tableInfo, len(stmt.From))
  276. for i, tref := range stmt.From {
  277. alias := tref.Alias
  278. if alias == "" {
  279. alias = tref.Name
  280. }
  281. sch, _ := e.schema.GetSchema(tref.Name)
  282. cols := map[string]bool{}
  283. if sch != nil {
  284. for _, c := range sch.Columns {
  285. cols[strings.ToLower(c.Name)] = true
  286. }
  287. }
  288. allTableInfos[i] = tableInfo{alias: alias, name: tref.Name, colsSet: cols}
  289. }
  290. // Split WHERE into AND-clauses and determine which tables each clause touches.
  291. var andClauses []parser.Expr
  292. if stmt.Where != nil {
  293. andClauses = splitANDClauses(stmt.Where)
  294. }
  295. // For each table, collect conditions that reference only its own columns.
  296. tableFilters := make([][]parser.Expr, len(stmt.From))
  297. var crossFilters []parser.Expr
  298. for _, clause := range andClauses {
  299. refs := collectColumnRefs(clause)
  300. ownerIdx := -1
  301. cross := false
  302. for _, ref := range refs {
  303. colLower := strings.ToLower(ref)
  304. found := -1
  305. for i, ti := range allTableInfos {
  306. if ti.colsSet[colLower] {
  307. if found == -1 {
  308. found = i
  309. } else if found != i {
  310. cross = true
  311. break
  312. }
  313. }
  314. }
  315. if cross {
  316. break
  317. }
  318. if found != -1 {
  319. if ownerIdx == -1 {
  320. ownerIdx = found
  321. } else if ownerIdx != found {
  322. cross = true
  323. break
  324. }
  325. }
  326. }
  327. if cross || ownerIdx == -1 {
  328. crossFilters = append(crossFilters, clause)
  329. } else {
  330. tableFilters[ownerIdx] = append(tableFilters[ownerIdx], clause)
  331. }
  332. }
  333. // Build cross-condition adjacency: for each cross filter, record which table indices it touches.
  334. type crossEdge struct{ a, b int }
  335. var crossEdges []crossEdge
  336. for _, clause := range crossFilters {
  337. refs := collectColumnRefs(clause)
  338. touched := map[int]bool{}
  339. for _, ref := range refs {
  340. cl := strings.ToLower(ref)
  341. for j, ti := range allTableInfos {
  342. if ti.colsSet[cl] {
  343. touched[j] = true
  344. }
  345. }
  346. }
  347. idxs := make([]int, 0, len(touched))
  348. for j := range touched {
  349. idxs = append(idxs, j)
  350. }
  351. if len(idxs) == 2 {
  352. crossEdges = append(crossEdges, crossEdge{idxs[0], idxs[1]})
  353. }
  354. }
  355. // Helper: find cross-conditions applicable when seenSet is fully present.
  356. applyWhenSeen := func(seenSet map[int]bool, pending []parser.Expr) (applicable, still []parser.Expr) {
  357. for _, clause := range pending {
  358. refs := collectColumnRefs(clause)
  359. ok := true
  360. for _, ref := range refs {
  361. cl := strings.ToLower(ref)
  362. found := false
  363. for j, tti := range allTableInfos {
  364. if tti.colsSet[cl] && seenSet[j] {
  365. found = true
  366. break
  367. }
  368. }
  369. if !found {
  370. ok = false
  371. break
  372. }
  373. }
  374. if ok {
  375. applicable = append(applicable, clause)
  376. } else {
  377. still = append(still, clause)
  378. }
  379. }
  380. return
  381. }
  382. // Helper: inline cross-join two row-sets, applying a predicate.
  383. inlineJoin := func(left, right []storage.Row, pred parser.Expr) []storage.Row {
  384. out := make([]storage.Row, 0, len(left))
  385. for _, l := range left {
  386. for _, r := range right {
  387. m := make(storage.Row, len(l)+len(r))
  388. for k, v := range l {
  389. m[k] = v
  390. }
  391. for k, v := range r {
  392. m[k] = v
  393. }
  394. if pred != nil {
  395. val, _ := e.evalExpr(pred, m)
  396. if !toBool(val) {
  397. continue
  398. }
  399. }
  400. out = append(out, m)
  401. }
  402. }
  403. return out
  404. }
  405. // Pre-join connected components of "cross-only" tables (0 single-table filters,
  406. // connected via cross conditions to other cross-only tables).
  407. // This prevents n^k explosions when bare tables are joined last.
  408. crossOnlySet := map[int]bool{}
  409. for i := range stmt.From {
  410. if len(tableFilters[i]) > 0 {
  411. continue
  412. }
  413. for _, ce := range crossEdges {
  414. if ce.a == i || ce.b == i {
  415. crossOnlySet[i] = true
  416. break
  417. }
  418. }
  419. }
  420. // BFS: find connected components among cross-only tables.
  421. compOf := make([]int, len(stmt.From))
  422. for i := range compOf {
  423. compOf[i] = -1
  424. }
  425. nComps := 0
  426. for start := range stmt.From {
  427. if !crossOnlySet[start] || compOf[start] != -1 {
  428. continue
  429. }
  430. queue := []int{start}
  431. compOf[start] = nComps
  432. for len(queue) > 0 {
  433. cur := queue[0]
  434. queue = queue[1:]
  435. for _, ce := range crossEdges {
  436. var nb int = -1
  437. if ce.a == cur && crossOnlySet[ce.b] {
  438. nb = ce.b
  439. } else if ce.b == cur && crossOnlySet[ce.a] {
  440. nb = ce.a
  441. }
  442. if nb >= 0 && compOf[nb] == -1 {
  443. compOf[nb] = nComps
  444. queue = append(queue, nb)
  445. }
  446. }
  447. }
  448. nComps++
  449. }
  450. // Group cross-only tables by component.
  451. compTbls := make([][]int, nComps)
  452. for i, c := range compOf {
  453. if c >= 0 {
  454. compTbls[c] = append(compTbls[c], i)
  455. }
  456. }
  457. // Pre-join each component with ≥2 tables; collect results as virtual units.
  458. type virtualUnit struct {
  459. tableIdxs map[int]bool
  460. rows []storage.Row
  461. }
  462. var virtuals []virtualUnit
  463. preJoined := map[int]bool{} // original table indices consumed into virtuals
  464. remaining := make([]parser.Expr, len(crossFilters))
  465. copy(remaining, crossFilters)
  466. for _, comp := range compTbls {
  467. if len(comp) < 2 {
  468. continue
  469. }
  470. // Pick seed: table with most cross-edges within component.
  471. seed := comp[0]
  472. for _, idx := range comp[1:] {
  473. degIdx, degSeed := 0, 0
  474. for _, ce := range crossEdges {
  475. if (ce.a == idx || ce.b == idx) {
  476. degIdx++
  477. }
  478. if (ce.a == seed || ce.b == seed) {
  479. degSeed++
  480. }
  481. }
  482. if degIdx > degSeed {
  483. seed = idx
  484. }
  485. }
  486. // Load seed.
  487. seedRows, rerr := e.table.Select(stmt.From[seed].Name, nil)
  488. if rerr != nil {
  489. return nil, rerr
  490. }
  491. for j := range seedRows {
  492. seedRows[j] = e.addTableAlias(seedRows[j], allTableInfos[seed].alias)
  493. }
  494. vSeen := map[int]bool{seed: true}
  495. // Greedy within-component join.
  496. compSet := map[int]bool{}
  497. for _, idx := range comp {
  498. compSet[idx] = true
  499. }
  500. for len(vSeen) < len(comp) {
  501. // Pick next table in component with cross-edge to vSeen.
  502. nextC := -1
  503. for _, idx := range comp {
  504. if vSeen[idx] {
  505. continue
  506. }
  507. for _, ce := range crossEdges {
  508. if (ce.a == idx && vSeen[ce.b]) || (ce.b == idx && vSeen[ce.a]) {
  509. nextC = idx
  510. break
  511. }
  512. }
  513. if nextC >= 0 {
  514. break
  515. }
  516. }
  517. if nextC < 0 {
  518. for _, idx := range comp {
  519. if !vSeen[idx] {
  520. nextC = idx
  521. break
  522. }
  523. }
  524. }
  525. nextRows, rerr := e.table.Select(stmt.From[nextC].Name, nil)
  526. if rerr != nil {
  527. return nil, rerr
  528. }
  529. for j := range nextRows {
  530. nextRows[j] = e.addTableAlias(nextRows[j], allTableInfos[nextC].alias)
  531. }
  532. vSeen[nextC] = true
  533. appl, still := applyWhenSeen(vSeen, remaining)
  534. remaining = still
  535. var pred parser.Expr
  536. if len(appl) > 0 {
  537. pred = combineAND(appl)
  538. }
  539. seedRows = inlineJoin(seedRows, nextRows, pred)
  540. }
  541. virtuals = append(virtuals, virtualUnit{tableIdxs: vSeen, rows: seedRows})
  542. for idx := range vSeen {
  543. preJoined[idx] = true
  544. }
  545. }
  546. // Build greedy order for non-pre-joined tables.
  547. // Score: single-table filter count + 1000 × cross-edges to already-joined.
  548. orderNonPJ := make([]int, 0, len(stmt.From)-len(preJoined))
  549. inOrderNPJ := make([]bool, len(stmt.From))
  550. best := -1
  551. for j := range stmt.From {
  552. if preJoined[j] {
  553. continue
  554. }
  555. if best < 0 || len(tableFilters[j]) > len(tableFilters[best]) {
  556. best = j
  557. }
  558. }
  559. if best >= 0 {
  560. orderNonPJ = append(orderNonPJ, best)
  561. inOrderNPJ[best] = true
  562. }
  563. for len(orderNonPJ)+len(preJoined) < len(stmt.From) {
  564. joined := map[int]bool{}
  565. for _, idx := range orderNonPJ {
  566. joined[idx] = true
  567. }
  568. nextIdx := -1
  569. nextScore := -1
  570. for j := range stmt.From {
  571. if inOrderNPJ[j] || preJoined[j] {
  572. continue
  573. }
  574. score := len(tableFilters[j])
  575. for _, ce := range crossEdges {
  576. if (ce.a == j && joined[ce.b]) || (ce.b == j && joined[ce.a]) {
  577. score += 1000
  578. }
  579. }
  580. if score > nextScore {
  581. nextScore = score
  582. nextIdx = j
  583. }
  584. }
  585. if nextIdx < 0 {
  586. for j := range stmt.From {
  587. if !inOrderNPJ[j] && !preJoined[j] {
  588. nextIdx = j
  589. break
  590. }
  591. }
  592. }
  593. if nextIdx >= 0 {
  594. orderNonPJ = append(orderNonPJ, nextIdx)
  595. inOrderNPJ[nextIdx] = true
  596. }
  597. }
  598. // Load the initial rows for the first non-pre-joined table (or use the already-loaded rows).
  599. seenTables := map[int]bool{}
  600. if len(orderNonPJ) > 0 {
  601. first := orderNonPJ[0]
  602. if first != 0 {
  603. rows, err = e.table.Select(stmt.From[first].Name, nil)
  604. if err != nil {
  605. return nil, err
  606. }
  607. for i := range rows {
  608. rows[i] = e.addTableAlias(rows[i], allTableInfos[first].alias)
  609. }
  610. }
  611. if len(tableFilters[first]) > 0 {
  612. pred := combineAND(tableFilters[first])
  613. var filtered []storage.Row
  614. for _, row := range rows {
  615. val, _ := e.evalExpr(pred, row)
  616. if toBool(val) {
  617. filtered = append(filtered, row)
  618. }
  619. }
  620. rows = filtered
  621. }
  622. seenTables[first] = true
  623. // Join remaining non-pre-joined tables.
  624. for _, idx := range orderNonPJ[1:] {
  625. ti := allTableInfos[idx]
  626. rightRows, rerr := e.table.Select(stmt.From[idx].Name, nil)
  627. if rerr != nil {
  628. return nil, rerr
  629. }
  630. for j := range rightRows {
  631. rightRows[j] = e.addTableAlias(rightRows[j], ti.alias)
  632. }
  633. if len(tableFilters[idx]) > 0 {
  634. pred := combineAND(tableFilters[idx])
  635. var filtered []storage.Row
  636. for _, row := range rightRows {
  637. val, _ := e.evalExpr(pred, row)
  638. if toBool(val) {
  639. filtered = append(filtered, row)
  640. }
  641. }
  642. rightRows = filtered
  643. }
  644. seenTables[idx] = true
  645. appl, still := applyWhenSeen(seenTables, remaining)
  646. remaining = still
  647. var pred parser.Expr
  648. if len(appl) > 0 {
  649. pred = combineAND(appl)
  650. }
  651. rows = inlineJoin(rows, rightRows, pred)
  652. }
  653. } else {
  654. // All tables were pre-joined; start with empty placeholder.
  655. rows = []storage.Row{{}}
  656. }
  657. // Integrate virtual (pre-joined) units into the result.
  658. for _, vu := range virtuals {
  659. for idx := range vu.tableIdxs {
  660. seenTables[idx] = true
  661. }
  662. appl, still := applyWhenSeen(seenTables, remaining)
  663. remaining = still
  664. var pred parser.Expr
  665. if len(appl) > 0 {
  666. pred = combineAND(appl)
  667. }
  668. rows = inlineJoin(rows, vu.rows, pred)
  669. }
  670. // Apply any remaining conditions (shouldn't normally happen).
  671. if len(remaining) > 0 {
  672. pred := combineAND(remaining)
  673. var filtered []storage.Row
  674. for _, row := range rows {
  675. val, _ := e.evalExpr(pred, row)
  676. if toBool(val) {
  677. filtered = append(filtered, row)
  678. }
  679. }
  680. rows = filtered
  681. }
  682. }
  683. // Handle GROUP BY
  684. if len(stmt.GroupBy) > 0 {
  685. return e.executeGroupBy(stmt, rows, schema)
  686. }
  687. // Check for aggregate functions without GROUP BY
  688. hasAggregate := e.hasAggregates(stmt.Columns)
  689. if hasAggregate {
  690. return e.executeAggregateSelect(stmt, rows, schema)
  691. }
  692. // Apply ORDER BY
  693. if len(stmt.OrderBy) > 0 {
  694. e.sortRows(rows, resolveOrderByPositions(stmt.OrderBy, stmt.Columns))
  695. }
  696. // Apply LIMIT/OFFSET
  697. if stmt.Offset != nil {
  698. offset := e.evalIntExpr(stmt.Offset)
  699. if offset < len(rows) {
  700. rows = rows[offset:]
  701. } else {
  702. rows = nil
  703. }
  704. }
  705. if stmt.Limit != nil {
  706. limit := e.evalIntExpr(stmt.Limit)
  707. if limit < len(rows) {
  708. rows = rows[:limit]
  709. }
  710. }
  711. // Build result
  712. result := NewResult("SELECT")
  713. // Determine columns
  714. for i, col := range stmt.Columns {
  715. if col.Alias != "" {
  716. result.AddColumn(col.Alias)
  717. } else if ref, ok := col.Expr.(*parser.ColumnRef); ok {
  718. result.AddColumn(ref.Column)
  719. } else if col.Star {
  720. // Handle SELECT * - add all columns from schema
  721. for _, c := range schema.Columns {
  722. result.AddColumn(c.Name)
  723. }
  724. } else {
  725. result.AddColumn(fmt.Sprintf("column%d", i+1))
  726. }
  727. }
  728. // Add rows - evaluate each select expression
  729. for _, row := range rows {
  730. values := make([]interface{}, 0)
  731. for _, col := range stmt.Columns {
  732. if col.Star {
  733. // For SELECT *, add all columns in order
  734. for _, c := range schema.Columns {
  735. if storage.IsRowIDColumn(c.Name) {
  736. values = append(values, row["_rowid_"])
  737. } else {
  738. values = append(values, row[c.Name])
  739. }
  740. }
  741. } else {
  742. // Evaluate the expression
  743. val, err := e.evalExpr(col.Expr, row)
  744. if err != nil {
  745. return nil, err
  746. }
  747. values = append(values, val)
  748. }
  749. }
  750. result.AddRow(values...)
  751. }
  752. // Apply DISTINCT if specified
  753. if stmt.Distinct {
  754. result.Rows = e.applyDistinct(result.Rows)
  755. }
  756. return result, nil
  757. }
  758. // executeCompound executes a compound SELECT (UNION / UNION ALL / INTERSECT / EXCEPT).
  759. func (e *Executor) executeCompound(c *parser.CompoundSelect) (*Result, error) {
  760. left, err := e.executeSelect(c.Left)
  761. if err != nil {
  762. return nil, err
  763. }
  764. right, err := e.executeSelect(c.Right)
  765. if err != nil {
  766. return nil, err
  767. }
  768. rowKey := func(row []interface{}) string {
  769. parts := make([]string, len(row))
  770. for i, v := range row {
  771. if v == nil {
  772. parts[i] = "\x00NULL"
  773. } else {
  774. parts[i] = fmt.Sprintf("%v", v)
  775. }
  776. }
  777. return strings.Join(parts, "\x01")
  778. }
  779. result := NewResult("SELECT")
  780. for _, col := range left.Columns {
  781. result.AddColumn(col)
  782. }
  783. switch c.Op {
  784. case parser.SetOpUnion:
  785. seen := map[string]bool{}
  786. for _, row := range left.Rows {
  787. k := rowKey(row)
  788. if !seen[k] {
  789. seen[k] = true
  790. result.AddRow(row...)
  791. }
  792. }
  793. for _, row := range right.Rows {
  794. k := rowKey(row)
  795. if !seen[k] {
  796. seen[k] = true
  797. result.AddRow(row...)
  798. }
  799. }
  800. case parser.SetOpUnionAll:
  801. for _, row := range left.Rows {
  802. result.AddRow(row...)
  803. }
  804. for _, row := range right.Rows {
  805. result.AddRow(row...)
  806. }
  807. case parser.SetOpIntersect:
  808. rightSet := map[string]bool{}
  809. for _, row := range right.Rows {
  810. rightSet[rowKey(row)] = true
  811. }
  812. seen := map[string]bool{}
  813. for _, row := range left.Rows {
  814. k := rowKey(row)
  815. if rightSet[k] && !seen[k] {
  816. seen[k] = true
  817. result.AddRow(row...)
  818. }
  819. }
  820. case parser.SetOpExcept:
  821. rightSet := map[string]bool{}
  822. for _, row := range right.Rows {
  823. rightSet[rowKey(row)] = true
  824. }
  825. seen := map[string]bool{}
  826. for _, row := range left.Rows {
  827. k := rowKey(row)
  828. if !rightSet[k] && !seen[k] {
  829. seen[k] = true
  830. result.AddRow(row...)
  831. }
  832. }
  833. }
  834. // Apply compound-level ORDER BY / LIMIT / OFFSET if present.
  835. if len(c.OrderBy) > 0 {
  836. e.sortResultRows(result, c.OrderBy, nil, nil)
  837. }
  838. if c.Limit != nil {
  839. limitVal, err := e.evalExpr(c.Limit, nil)
  840. if err == nil {
  841. limit := int(toFloat(limitVal))
  842. if limit < len(result.Rows) {
  843. result.Rows = result.Rows[:limit]
  844. }
  845. }
  846. }
  847. if c.Offset != nil {
  848. offsetVal, err := e.evalExpr(c.Offset, nil)
  849. if err == nil {
  850. offset := int(toFloat(offsetVal))
  851. if offset >= len(result.Rows) {
  852. result.Rows = nil
  853. } else if offset > 0 {
  854. result.Rows = result.Rows[offset:]
  855. }
  856. }
  857. }
  858. return result, nil
  859. }
  860. // executeSelectExpr executes a SELECT without FROM.
  861. func (e *Executor) executeSelectExpr(stmt *parser.SelectStmt) (*Result, error) {
  862. result := NewResult("SELECT")
  863. // Determine columns
  864. for i, col := range stmt.Columns {
  865. if col.Alias != "" {
  866. result.AddColumn(col.Alias)
  867. } else {
  868. result.AddColumn(fmt.Sprintf("column%d", i+1))
  869. }
  870. }
  871. // Evaluate expressions
  872. values := make([]interface{}, len(stmt.Columns))
  873. for i, col := range stmt.Columns {
  874. val, err := e.evalExpr(col.Expr, nil)
  875. if err != nil {
  876. return nil, err
  877. }
  878. values[i] = val
  879. }
  880. result.AddRow(values...)
  881. return result, nil
  882. }
  883. // executeSelectFromSubquery executes a SELECT with a subquery in FROM clause.
  884. func (e *Executor) executeSelectFromSubquery(stmt *parser.SelectStmt) (*Result, error) {
  885. // Execute the subquery to get the derived table
  886. subqueryResult, err := e.executeSelect(stmt.From[0].Subquery)
  887. if err != nil {
  888. return nil, fmt.Errorf("subquery error: %w", err)
  889. }
  890. // Convert subquery result to rows for further processing
  891. derivedRows := make([]storage.Row, 0, subqueryResult.RowCount)
  892. for _, rowValues := range subqueryResult.Rows {
  893. row := make(storage.Row)
  894. for i, col := range subqueryResult.Columns {
  895. row[col] = rowValues[i]
  896. }
  897. derivedRows = append(derivedRows, row)
  898. }
  899. // Handle JOINs if present
  900. if stmt.From[0].Join != nil {
  901. derivedRows, err = e.executeJoin(stmt.From[0], derivedRows)
  902. if err != nil {
  903. return nil, err
  904. }
  905. }
  906. // Apply WHERE clause on derived table
  907. if stmt.Where != nil {
  908. filteredRows := make([]storage.Row, 0)
  909. for _, row := range derivedRows {
  910. val, err := e.evalExpr(stmt.Where, row)
  911. if err != nil {
  912. continue
  913. }
  914. if toBool(val) {
  915. filteredRows = append(filteredRows, row)
  916. }
  917. }
  918. derivedRows = filteredRows
  919. }
  920. // Handle GROUP BY
  921. if len(stmt.GroupBy) > 0 {
  922. // Create a temporary schema from subquery columns
  923. tempSchema := &storage.Schema{
  924. Name: "derived",
  925. Columns: make([]storage.Column, len(subqueryResult.Columns)),
  926. }
  927. for i, col := range subqueryResult.Columns {
  928. tempSchema.Columns[i] = storage.Column{
  929. Name: col,
  930. Type: "ANY",
  931. }
  932. }
  933. return e.executeGroupBy(stmt, derivedRows, tempSchema)
  934. }
  935. // Check for aggregate functions without GROUP BY
  936. hasAggregate := e.hasAggregates(stmt.Columns)
  937. if hasAggregate {
  938. tempSchema := &storage.Schema{
  939. Name: "derived",
  940. Columns: make([]storage.Column, len(subqueryResult.Columns)),
  941. }
  942. for i, col := range subqueryResult.Columns {
  943. tempSchema.Columns[i] = storage.Column{
  944. Name: col,
  945. Type: "ANY",
  946. }
  947. }
  948. return e.executeAggregateSelect(stmt, derivedRows, tempSchema)
  949. }
  950. // Apply ORDER BY
  951. if len(stmt.OrderBy) > 0 {
  952. e.sortRows(derivedRows, resolveOrderByPositions(stmt.OrderBy, stmt.Columns))
  953. }
  954. // Apply LIMIT/OFFSET
  955. if stmt.Offset != nil {
  956. offset := e.evalIntExpr(stmt.Offset)
  957. if offset < len(derivedRows) {
  958. derivedRows = derivedRows[offset:]
  959. } else {
  960. derivedRows = nil
  961. }
  962. }
  963. if stmt.Limit != nil {
  964. limit := e.evalIntExpr(stmt.Limit)
  965. if limit < len(derivedRows) {
  966. derivedRows = derivedRows[:limit]
  967. }
  968. }
  969. // Build result
  970. result := NewResult("SELECT")
  971. // Determine output columns
  972. if stmt.Columns[0].Star {
  973. // SELECT * from derived table
  974. for _, col := range subqueryResult.Columns {
  975. result.AddColumn(col)
  976. }
  977. } else {
  978. // Specific columns
  979. for _, col := range stmt.Columns {
  980. if col.Alias != "" {
  981. result.AddColumn(col.Alias)
  982. } else if colRef, ok := col.Expr.(*parser.ColumnRef); ok {
  983. result.AddColumn(colRef.Column)
  984. } else {
  985. result.AddColumn("column")
  986. }
  987. }
  988. }
  989. // Add rows
  990. for _, row := range derivedRows {
  991. if stmt.Columns[0].Star {
  992. // SELECT * - use all columns
  993. values := make([]interface{}, len(subqueryResult.Columns))
  994. for i, col := range subqueryResult.Columns {
  995. values[i] = row[col]
  996. }
  997. result.AddRow(values...)
  998. } else {
  999. // Specific columns - evaluate expressions
  1000. values := make([]interface{}, len(stmt.Columns))
  1001. for i, col := range stmt.Columns {
  1002. val, err := e.evalExpr(col.Expr, row)
  1003. if err != nil {
  1004. return nil, err
  1005. }
  1006. values[i] = val
  1007. }
  1008. result.AddRow(values...)
  1009. }
  1010. }
  1011. return result, nil
  1012. }
  1013. // executeAggregateSelect executes a SELECT with aggregate functions.
  1014. func (e *Executor) executeAggregateSelect(stmt *parser.SelectStmt, rows []storage.Row, schema *storage.Schema) (*Result, error) {
  1015. result := NewResult("SELECT")
  1016. // Determine columns and evaluate aggregates
  1017. for i, col := range stmt.Columns {
  1018. if col.Alias != "" {
  1019. result.AddColumn(col.Alias)
  1020. } else if col.Star {
  1021. result.AddColumn("*")
  1022. } else {
  1023. result.AddColumn(fmt.Sprintf("column%d", i+1))
  1024. }
  1025. }
  1026. // Calculate values
  1027. values := make([]interface{}, len(stmt.Columns))
  1028. for i, col := range stmt.Columns {
  1029. val, err := e.evalAggregateExpr(col.Expr, rows)
  1030. if err != nil {
  1031. return nil, err
  1032. }
  1033. values[i] = val
  1034. }
  1035. result.AddRow(values...)
  1036. return result, nil
  1037. }
  1038. // executeGroupBy executes a GROUP BY query.
  1039. func (e *Executor) executeGroupBy(stmt *parser.SelectStmt, rows []storage.Row, schema *storage.Schema) (*Result, error) {
  1040. // Group rows
  1041. groups := make(map[string][]storage.Row)
  1042. for _, row := range rows {
  1043. key := e.buildGroupKey(stmt.GroupBy, row)
  1044. groups[key] = append(groups[key], row)
  1045. }
  1046. result := NewResult("SELECT")
  1047. // Determine columns
  1048. columnNames := make([]string, len(stmt.Columns))
  1049. for i, col := range stmt.Columns {
  1050. if col.Alias != "" {
  1051. columnNames[i] = col.Alias
  1052. result.AddColumn(col.Alias)
  1053. } else if ref, ok := col.Expr.(*parser.ColumnRef); ok {
  1054. columnNames[i] = ref.Column
  1055. result.AddColumn(ref.Column)
  1056. } else {
  1057. columnNames[i] = fmt.Sprintf("column%d", i+1)
  1058. result.AddColumn(columnNames[i])
  1059. }
  1060. }
  1061. // Process each group
  1062. for _, groupRows := range groups {
  1063. // Apply HAVING
  1064. if stmt.Having != nil {
  1065. val, err := e.evalAggregateExpr(stmt.Having, groupRows)
  1066. if err != nil {
  1067. continue
  1068. }
  1069. if !toBool(val) {
  1070. continue
  1071. }
  1072. }
  1073. values := make([]interface{}, len(stmt.Columns))
  1074. for i, col := range stmt.Columns {
  1075. if e.isAggregate(col.Expr) {
  1076. val, err := e.evalAggregateExpr(col.Expr, groupRows)
  1077. if err != nil {
  1078. return nil, err
  1079. }
  1080. values[i] = val
  1081. } else {
  1082. // Use first row's value for non-aggregate columns
  1083. val, err := e.evalExpr(col.Expr, groupRows[0])
  1084. if err != nil {
  1085. return nil, err
  1086. }
  1087. values[i] = val
  1088. }
  1089. }
  1090. result.AddRow(values...)
  1091. }
  1092. // Apply ORDER BY
  1093. if len(stmt.OrderBy) > 0 {
  1094. e.sortResultRows(result, stmt.OrderBy, stmt.Columns, columnNames)
  1095. }
  1096. // Apply LIMIT/OFFSET
  1097. if stmt.Offset != nil {
  1098. offset := e.evalIntExpr(stmt.Offset)
  1099. if offset < len(result.Rows) {
  1100. result.Rows = result.Rows[offset:]
  1101. } else {
  1102. result.Rows = nil
  1103. }
  1104. result.RowCount = len(result.Rows)
  1105. }
  1106. if stmt.Limit != nil {
  1107. limit := e.evalIntExpr(stmt.Limit)
  1108. if limit < len(result.Rows) {
  1109. result.Rows = result.Rows[:limit]
  1110. }
  1111. result.RowCount = len(result.Rows)
  1112. }
  1113. return result, nil
  1114. }
  1115. // executeJoins recursively processes all JOIN clauses in a table reference.
  1116. func (e *Executor) executeJoins(tableRef parser.TableRef, leftRows []storage.Row) ([]storage.Row, error) {
  1117. if tableRef.Join == nil || tableRef.Join.Table == nil {
  1118. return leftRows, nil
  1119. }
  1120. // Get the right table name and its data
  1121. rightTableRef := tableRef.Join.Table
  1122. rightTable := rightTableRef.Name
  1123. rightRows, err := e.table.Select(rightTable, nil)
  1124. if err != nil {
  1125. return nil, err
  1126. }
  1127. // Perform the join between left and right
  1128. var result []storage.Row
  1129. leftTableName := tableRef.Name
  1130. leftAlias := tableRef.Alias
  1131. rightAlias := rightTableRef.Alias
  1132. // If leftAlias is empty, use the table name
  1133. if leftAlias == "" {
  1134. leftAlias = leftTableName
  1135. }
  1136. if rightAlias == "" {
  1137. rightAlias = rightTable
  1138. }
  1139. switch tableRef.Join.Type {
  1140. case parser.JoinInner:
  1141. for _, left := range leftRows {
  1142. for _, right := range rightRows {
  1143. merged := e.mergeRows(left, right, leftAlias, rightAlias)
  1144. if tableRef.Join.Condition != nil {
  1145. match, _ := e.evalExpr(tableRef.Join.Condition, merged)
  1146. if toBool(match) {
  1147. result = append(result, merged)
  1148. }
  1149. } else {
  1150. result = append(result, merged)
  1151. }
  1152. }
  1153. }
  1154. case parser.JoinLeft:
  1155. for _, left := range leftRows {
  1156. matched := false
  1157. for _, right := range rightRows {
  1158. merged := e.mergeRows(left, right, leftAlias, rightAlias)
  1159. if tableRef.Join.Condition != nil {
  1160. match, _ := e.evalExpr(tableRef.Join.Condition, merged)
  1161. if toBool(match) {
  1162. result = append(result, merged)
  1163. matched = true
  1164. }
  1165. }
  1166. }
  1167. if !matched {
  1168. // Add left row with nulls for right
  1169. result = append(result, left)
  1170. }
  1171. }
  1172. case parser.JoinCross:
  1173. for _, left := range leftRows {
  1174. for _, right := range rightRows {
  1175. result = append(result, e.mergeRows(left, right, leftAlias, rightAlias))
  1176. }
  1177. }
  1178. }
  1179. // Recursively process any additional joins
  1180. if rightTableRef.Join != nil {
  1181. return e.executeJoins(*rightTableRef, result)
  1182. }
  1183. return result, nil
  1184. }
  1185. // executeJoin executes a JOIN operation.
  1186. func (e *Executor) executeJoin(tableRef parser.TableRef, leftRows []storage.Row) ([]storage.Row, error) {
  1187. join := tableRef.Join
  1188. if join == nil || join.Table == nil {
  1189. return leftRows, nil
  1190. }
  1191. rightTable := join.Table.Name
  1192. rightRows, err := e.table.Select(rightTable, nil)
  1193. if err != nil {
  1194. return nil, err
  1195. }
  1196. var result []storage.Row
  1197. switch join.Type {
  1198. case parser.JoinInner:
  1199. for _, left := range leftRows {
  1200. for _, right := range rightRows {
  1201. merged := e.mergeRows(left, right, tableRef.Alias, join.Table.Alias)
  1202. if join.Condition != nil {
  1203. match, _ := e.evalExpr(join.Condition, merged)
  1204. if toBool(match) {
  1205. result = append(result, merged)
  1206. }
  1207. } else {
  1208. result = append(result, merged)
  1209. }
  1210. }
  1211. }
  1212. case parser.JoinLeft:
  1213. for _, left := range leftRows {
  1214. matched := false
  1215. for _, right := range rightRows {
  1216. merged := e.mergeRows(left, right, tableRef.Alias, join.Table.Alias)
  1217. if join.Condition != nil {
  1218. match, _ := e.evalExpr(join.Condition, merged)
  1219. if toBool(match) {
  1220. result = append(result, merged)
  1221. matched = true
  1222. }
  1223. }
  1224. }
  1225. if !matched {
  1226. // Add left row with nulls for right
  1227. result = append(result, left)
  1228. }
  1229. }
  1230. case parser.JoinCross:
  1231. for _, left := range leftRows {
  1232. for _, right := range rightRows {
  1233. result = append(result, e.mergeRows(left, right, tableRef.Alias, join.Table.Alias))
  1234. }
  1235. }
  1236. }
  1237. return result, nil
  1238. }
  1239. // mergeRows merges two rows with optional table aliases.
  1240. func (e *Executor) mergeRows(left, right storage.Row, leftAlias, rightAlias string) storage.Row {
  1241. result := make(storage.Row)
  1242. for k, v := range left {
  1243. // Copy the key as-is (it might already be qualified)
  1244. result[k] = v
  1245. // Only add qualified name if the key is NOT already qualified and we have an alias
  1246. if leftAlias != "" && !strings.Contains(k, ".") {
  1247. result[leftAlias+"."+k] = v
  1248. }
  1249. }
  1250. for k, v := range right {
  1251. // For unqualified names, only add if they don't already exist
  1252. // This prevents right table columns from overwriting left table columns
  1253. if !strings.Contains(k, ".") {
  1254. if _, exists := result[k]; !exists {
  1255. result[k] = v
  1256. }
  1257. // Add qualified name for right table
  1258. if rightAlias != "" {
  1259. result[rightAlias+"."+k] = v
  1260. }
  1261. } else {
  1262. // Already qualified, just copy it
  1263. result[k] = v
  1264. }
  1265. }
  1266. return result
  1267. }
  1268. // addTableAlias adds table-qualified names to a row.
  1269. func (e *Executor) addTableAlias(row storage.Row, alias string) storage.Row {
  1270. result := make(storage.Row)
  1271. for k, v := range row {
  1272. result[k] = v
  1273. // Don't add alias to already-qualified names
  1274. if !strings.Contains(k, ".") {
  1275. result[alias+"."+k] = v
  1276. }
  1277. }
  1278. return result
  1279. }
  1280. // executeInsert executes an INSERT statement.
  1281. func (e *Executor) executeInsert(stmt *parser.InsertStmt) (*Result, error) {
  1282. tableName := stmt.Table.Name
  1283. schema, err := e.schema.GetSchema(tableName)
  1284. if err != nil {
  1285. return nil, err
  1286. }
  1287. // INSERT ... SELECT: materialise the SELECT result and bulk-insert.
  1288. if stmt.Select != nil {
  1289. sel, err := e.executeSelect(stmt.Select)
  1290. if err != nil {
  1291. return nil, err
  1292. }
  1293. rows := make([]storage.Row, 0, len(sel.Rows))
  1294. for _, selRow := range sel.Rows {
  1295. row := make(storage.Row)
  1296. if len(stmt.Columns) > 0 {
  1297. for i, col := range stmt.Columns {
  1298. if i < len(selRow) {
  1299. row[col] = selRow[i]
  1300. }
  1301. }
  1302. } else {
  1303. for i, col := range schema.Columns {
  1304. if i < len(selRow) {
  1305. row[col.Name] = selRow[i]
  1306. }
  1307. }
  1308. }
  1309. rows = append(rows, row)
  1310. }
  1311. count, err := e.table.InsertBulk(tableName, rows)
  1312. if err != nil {
  1313. return nil, err
  1314. }
  1315. result := NewResult("INSERT")
  1316. result.SetRowCount(count)
  1317. return result, nil
  1318. }
  1319. count := 0
  1320. for _, values := range stmt.Values {
  1321. row := make(storage.Row)
  1322. if len(stmt.Columns) > 0 {
  1323. // Named columns
  1324. for i, col := range stmt.Columns {
  1325. if i < len(values) {
  1326. val, err := e.evalExpr(values[i], nil)
  1327. if err != nil {
  1328. return nil, err
  1329. }
  1330. row[col] = val
  1331. }
  1332. }
  1333. } else {
  1334. // All columns in order
  1335. for i, col := range schema.Columns {
  1336. if i < len(values) {
  1337. val, err := e.evalExpr(values[i], nil)
  1338. if err != nil {
  1339. return nil, err
  1340. }
  1341. row[col.Name] = val
  1342. }
  1343. }
  1344. }
  1345. err := e.table.Insert(tableName, row)
  1346. if err != nil {
  1347. // Handle conflict based on OnConflict action
  1348. if strings.Contains(err.Error(), "duplicate") {
  1349. switch stmt.OnConflict {
  1350. case parser.ConflictIgnore:
  1351. // Silently ignore the duplicate
  1352. continue
  1353. case parser.ConflictReplace:
  1354. // Delete existing row and insert new one
  1355. pkValue := row[schema.PrimaryKey]
  1356. if pkValue != nil {
  1357. e.table.Delete(tableName, func(r storage.Row) bool {
  1358. return fmt.Sprintf("%v", r[schema.PrimaryKey]) == fmt.Sprintf("%v", pkValue)
  1359. })
  1360. // Try insert again
  1361. if err := e.table.Insert(tableName, row); err != nil {
  1362. return nil, err
  1363. }
  1364. }
  1365. case parser.ConflictAbort, parser.ConflictFail:
  1366. return nil, err
  1367. case parser.ConflictRollback:
  1368. // In a real implementation, this would rollback the transaction
  1369. return nil, err
  1370. default:
  1371. return nil, err
  1372. }
  1373. } else {
  1374. return nil, err
  1375. }
  1376. }
  1377. count++
  1378. }
  1379. result := NewResult("INSERT")
  1380. result.SetRowCount(count)
  1381. return result, nil
  1382. }
  1383. // executeUpdate executes an UPDATE statement.
  1384. func (e *Executor) executeUpdate(stmt *parser.UpdateStmt) (*Result, error) {
  1385. tableName := stmt.Table.Name
  1386. // Build filter
  1387. var filter func(storage.Row) bool
  1388. if stmt.Where != nil {
  1389. filter = func(row storage.Row) bool {
  1390. val, err := e.evalExpr(stmt.Where, row)
  1391. if err != nil {
  1392. return false
  1393. }
  1394. return toBool(val)
  1395. }
  1396. }
  1397. // Use UpdateFunc to evaluate expressions per-row (supports self-referencing like balance = balance + 100)
  1398. updateFn := func(row storage.Row) (storage.Row, error) {
  1399. updates := make(storage.Row)
  1400. for _, assign := range stmt.Set {
  1401. val, err := e.evalExpr(assign.Value, row)
  1402. if err != nil {
  1403. return nil, err
  1404. }
  1405. updates[assign.Column] = val
  1406. }
  1407. return updates, nil
  1408. }
  1409. count, err := e.table.UpdateFunc(tableName, updateFn, filter)
  1410. if err != nil {
  1411. return nil, err
  1412. }
  1413. result := NewResult("UPDATE")
  1414. result.SetRowCount(count)
  1415. return result, nil
  1416. }
  1417. // executeDelete executes a DELETE statement.
  1418. func (e *Executor) executeDelete(stmt *parser.DeleteStmt) (*Result, error) {
  1419. tableName := stmt.Table.Name
  1420. // Build filter
  1421. var filter func(storage.Row) bool
  1422. if stmt.Where != nil {
  1423. filter = func(row storage.Row) bool {
  1424. val, err := e.evalExpr(stmt.Where, row)
  1425. if err != nil {
  1426. return false
  1427. }
  1428. return toBool(val)
  1429. }
  1430. }
  1431. count, err := e.table.Delete(tableName, filter)
  1432. if err != nil {
  1433. return nil, err
  1434. }
  1435. result := NewResult("DELETE")
  1436. result.SetRowCount(count)
  1437. return result, nil
  1438. }
  1439. // executeCreateTable executes a CREATE TABLE statement.
  1440. func (e *Executor) executeCreateTable(stmt *parser.CreateTableStmt) (*Result, error) {
  1441. // Check if exists
  1442. if e.schema.TableExists(stmt.Table.Name) {
  1443. if stmt.IfNotExists {
  1444. result := NewResult("CREATE TABLE")
  1445. return result, nil
  1446. }
  1447. return nil, fmt.Errorf("table already exists: %s", stmt.Table.Name)
  1448. }
  1449. // Build schema
  1450. schema := &storage.Schema{
  1451. Name: stmt.Table.Name,
  1452. }
  1453. for _, colDef := range stmt.Columns {
  1454. col := storage.Column{
  1455. Name: colDef.Name,
  1456. Type: colDef.Type.Name,
  1457. Nullable: true,
  1458. }
  1459. for _, constraint := range colDef.Constraints {
  1460. switch constraint.Type {
  1461. case parser.ConstraintPrimaryKey:
  1462. col.PrimaryKey = true
  1463. col.Nullable = false
  1464. schema.PrimaryKey = col.Name
  1465. case parser.ConstraintNotNull:
  1466. col.Nullable = false
  1467. case parser.ConstraintDefault:
  1468. if constraint.Default != nil {
  1469. val, _ := e.evalExpr(constraint.Default, nil)
  1470. col.Default = val
  1471. }
  1472. case parser.ConstraintAutoIncrement:
  1473. schema.AutoIncrement = true
  1474. }
  1475. }
  1476. schema.Columns = append(schema.Columns, col)
  1477. }
  1478. // Handle table-level constraints
  1479. for _, constraint := range stmt.Constraints {
  1480. if constraint.Type == parser.ConstraintPrimaryKey && len(constraint.Columns) > 0 {
  1481. schema.PrimaryKey = constraint.Columns[0]
  1482. for i := range schema.Columns {
  1483. if strings.EqualFold(schema.Columns[i].Name, schema.PrimaryKey) {
  1484. schema.Columns[i].PrimaryKey = true
  1485. schema.Columns[i].Nullable = false
  1486. }
  1487. }
  1488. }
  1489. }
  1490. if err := e.schema.CreateTable(schema); err != nil {
  1491. return nil, err
  1492. }
  1493. // Update analyzer catalog
  1494. e.catalog.CreateTable(schema.ToAnalyzerTableInfo())
  1495. result := NewResult("CREATE TABLE")
  1496. return result, nil
  1497. }
  1498. // executeDropTable executes a DROP TABLE statement.
  1499. func (e *Executor) executeDropTable(stmt *parser.DropTableStmt) (*Result, error) {
  1500. for _, tableRef := range stmt.Tables {
  1501. if !e.schema.TableExists(tableRef.Name) {
  1502. if stmt.IfExists {
  1503. continue
  1504. }
  1505. return nil, fmt.Errorf("table not found: %s", tableRef.Name)
  1506. }
  1507. // First, drop all indexes associated with this table
  1508. indexes, _ := e.schema.ListTableIndexes(tableRef.Name)
  1509. for _, idx := range indexes {
  1510. // Clear index entries
  1511. columns := make([]string, len(idx.Columns))
  1512. for i, col := range idx.Columns {
  1513. columns[i] = col.Name
  1514. }
  1515. e.table.ClearIndex(idx.Name, tableRef.Name, columns)
  1516. // Drop the index schema
  1517. e.schema.DropIndex(idx.Name)
  1518. }
  1519. // Then, truncate all data rows
  1520. e.table.Truncate(tableRef.Name)
  1521. // Finally, drop the table schema
  1522. if err := e.schema.DropTable(tableRef.Name); err != nil {
  1523. return nil, err
  1524. }
  1525. // Update analyzer catalog
  1526. e.catalog.DropTable(tableRef.Name)
  1527. }
  1528. result := NewResult("DROP TABLE")
  1529. return result, nil
  1530. }
  1531. // executeCreateIndex creates a new index.
  1532. func (e *Executor) executeCreateIndex(stmt *parser.CreateIndexStmt) (*Result, error) {
  1533. // Check if index already exists
  1534. if e.schema.IndexExists(stmt.Name) {
  1535. if stmt.IfNotExists {
  1536. result := NewResult("CREATE INDEX")
  1537. return result, nil
  1538. }
  1539. return nil, fmt.Errorf("index already exists: %s", stmt.Name)
  1540. }
  1541. // Verify table exists
  1542. if !e.schema.TableExists(stmt.Table) {
  1543. return nil, fmt.Errorf("table not found: %s", stmt.Table)
  1544. }
  1545. // Verify columns exist
  1546. schema, err := e.schema.GetSchema(stmt.Table)
  1547. if err != nil {
  1548. return nil, err
  1549. }
  1550. for _, col := range stmt.Columns {
  1551. if _, found := schema.GetColumn(col.Name); !found {
  1552. return nil, fmt.Errorf("column not found: %s", col.Name)
  1553. }
  1554. }
  1555. // Create storage index
  1556. index := &storage.Index{
  1557. Name: stmt.Name,
  1558. Table: stmt.Table,
  1559. Unique: stmt.Unique,
  1560. }
  1561. for _, col := range stmt.Columns {
  1562. index.Columns = append(index.Columns, storage.IndexColumn{
  1563. Name: col.Name,
  1564. Desc: col.Desc,
  1565. })
  1566. }
  1567. if err := e.schema.CreateIndex(index); err != nil {
  1568. return nil, err
  1569. }
  1570. // Build index entries for existing rows
  1571. columns := make([]string, len(stmt.Columns))
  1572. for i, col := range stmt.Columns {
  1573. columns[i] = col.Name
  1574. }
  1575. if err := e.table.BuildIndex(stmt.Name, stmt.Table, columns); err != nil {
  1576. // Rollback index creation on failure
  1577. e.schema.DropIndex(stmt.Name)
  1578. return nil, fmt.Errorf("failed to build index: %w", err)
  1579. }
  1580. result := NewResult("CREATE INDEX")
  1581. return result, nil
  1582. }
  1583. // executeDropIndex drops an index.
  1584. func (e *Executor) executeDropIndex(stmt *parser.DropIndexStmt) (*Result, error) {
  1585. if !e.schema.IndexExists(stmt.Name) {
  1586. if stmt.IfExists {
  1587. result := NewResult("DROP INDEX")
  1588. return result, nil
  1589. }
  1590. return nil, fmt.Errorf("index not found: %s", stmt.Name)
  1591. }
  1592. // Get index info to clear entries
  1593. index, err := e.schema.GetIndex(stmt.Name)
  1594. if err == nil && index != nil {
  1595. columns := make([]string, len(index.Columns))
  1596. for i, col := range index.Columns {
  1597. columns[i] = col.Name
  1598. }
  1599. e.table.ClearIndex(stmt.Name, index.Table, columns)
  1600. }
  1601. if err := e.schema.DropIndex(stmt.Name); err != nil {
  1602. return nil, err
  1603. }
  1604. result := NewResult("DROP INDEX")
  1605. return result, nil
  1606. }
  1607. func (e *Executor) executeCreateView(stmt *parser.CreateViewStmt) (*Result, error) {
  1608. name := strings.ToLower(stmt.View.Name)
  1609. if _, exists := e.views[name]; exists {
  1610. if stmt.IfNotExists {
  1611. return NewResult("CREATE VIEW"), nil
  1612. }
  1613. return nil, fmt.Errorf("view already exists: %s", stmt.View.Name)
  1614. }
  1615. e.views[name] = stmt.Select
  1616. // Register in catalog so the analyzer accepts SELECT FROM this view.
  1617. e.catalog.CreateTable(&analyzer.TableInfo{ //nolint:errcheck
  1618. Name: stmt.View.Name,
  1619. IsView: true,
  1620. })
  1621. return NewResult("CREATE VIEW"), nil
  1622. }
  1623. func (e *Executor) executeDropView(stmt *parser.DropViewStmt) (*Result, error) {
  1624. for _, ref := range stmt.Views {
  1625. name := strings.ToLower(ref.Name)
  1626. if _, exists := e.views[name]; !exists {
  1627. if stmt.IfExists {
  1628. continue
  1629. }
  1630. return nil, fmt.Errorf("view not found: %s", ref.Name)
  1631. }
  1632. delete(e.views, name)
  1633. e.catalog.DropTable(ref.Name) //nolint:errcheck
  1634. }
  1635. return NewResult("DROP VIEW"), nil
  1636. }
  1637. // executeAlterTable executes an ALTER TABLE statement.
  1638. func (e *Executor) executeAlterTable(stmt *parser.AlterTableStmt) (*Result, error) {
  1639. switch action := stmt.Action.(type) {
  1640. case *parser.AddColumnAction:
  1641. return e.executeAlterTableAddColumn(stmt.Table, action)
  1642. case *parser.DropColumnAction:
  1643. return e.executeAlterTableDropColumn(stmt.Table, action)
  1644. case *parser.RenameTableAction:
  1645. return e.executeAlterTableRename(stmt.Table, action)
  1646. case *parser.RenameColumnAction:
  1647. return e.executeAlterTableRenameColumn(stmt.Table, action)
  1648. default:
  1649. return nil, fmt.Errorf("unsupported ALTER TABLE action: %T", action)
  1650. }
  1651. }
  1652. // executeAlterTableAddColumn adds a column to a table.
  1653. func (e *Executor) executeAlterTableAddColumn(table string, action *parser.AddColumnAction) (*Result, error) {
  1654. col := storage.Column{
  1655. Name: action.Column.Name,
  1656. Type: action.Column.Type.Name,
  1657. Nullable: true,
  1658. }
  1659. // Process column constraints
  1660. for _, constraint := range action.Column.Constraints {
  1661. switch constraint.Type {
  1662. case parser.ConstraintPrimaryKey:
  1663. col.PrimaryKey = true
  1664. col.Nullable = false
  1665. case parser.ConstraintNotNull:
  1666. col.Nullable = false
  1667. case parser.ConstraintDefault:
  1668. if constraint.Default != nil {
  1669. val, _ := e.evalExpr(constraint.Default, nil)
  1670. col.Default = val
  1671. }
  1672. }
  1673. }
  1674. if err := e.schema.AddColumn(table, col); err != nil {
  1675. return nil, err
  1676. }
  1677. // Update catalog
  1678. e.SyncCatalog()
  1679. result := NewResult("ALTER TABLE")
  1680. return result, nil
  1681. }
  1682. // executeAlterTableDropColumn drops a column from a table.
  1683. func (e *Executor) executeAlterTableDropColumn(table string, action *parser.DropColumnAction) (*Result, error) {
  1684. if err := e.schema.DropColumn(table, action.Column); err != nil {
  1685. return nil, err
  1686. }
  1687. // Update catalog
  1688. e.SyncCatalog()
  1689. result := NewResult("ALTER TABLE")
  1690. return result, nil
  1691. }
  1692. // executeAlterTableRename renames a table.
  1693. func (e *Executor) executeAlterTableRename(table string, action *parser.RenameTableAction) (*Result, error) {
  1694. if err := e.schema.RenameTable(table, action.NewName); err != nil {
  1695. return nil, err
  1696. }
  1697. // Update catalog
  1698. e.SyncCatalog()
  1699. result := NewResult("ALTER TABLE")
  1700. return result, nil
  1701. }
  1702. // executeAlterTableRenameColumn renames a column.
  1703. func (e *Executor) executeAlterTableRenameColumn(table string, action *parser.RenameColumnAction) (*Result, error) {
  1704. if err := e.schema.RenameColumn(table, action.OldName, action.NewName); err != nil {
  1705. return nil, err
  1706. }
  1707. // Update catalog
  1708. e.SyncCatalog()
  1709. result := NewResult("ALTER TABLE")
  1710. return result, nil
  1711. }
  1712. // Transaction execution methods
  1713. // executeBegin starts a new transaction.
  1714. func (e *Executor) executeBegin(stmt *parser.BeginStmt) (*Result, error) {
  1715. if e.inTransaction {
  1716. return nil, fmt.Errorf("cannot start a transaction within a transaction")
  1717. }
  1718. e.inTransaction = true
  1719. e.savepoints = nil
  1720. e.txLog = nil
  1721. result := NewResult("BEGIN")
  1722. return result, nil
  1723. }
  1724. // executeCommit commits the current transaction.
  1725. func (e *Executor) executeCommit(stmt *parser.CommitStmt) (*Result, error) {
  1726. if !e.inTransaction {
  1727. return nil, fmt.Errorf("cannot commit: no transaction in progress")
  1728. }
  1729. // Clear transaction state
  1730. e.inTransaction = false
  1731. e.savepoints = nil
  1732. e.txLog = nil
  1733. result := NewResult("COMMIT")
  1734. return result, nil
  1735. }
  1736. // executeRollback rolls back the current transaction or to a savepoint.
  1737. func (e *Executor) executeRollback(stmt *parser.RollbackStmt) (*Result, error) {
  1738. if !e.inTransaction {
  1739. return nil, fmt.Errorf("cannot rollback: no transaction in progress")
  1740. }
  1741. if stmt.Savepoint != "" {
  1742. // Rollback to savepoint
  1743. return e.rollbackToSavepoint(stmt.Savepoint)
  1744. }
  1745. // Full rollback - undo all operations in reverse order
  1746. for i := len(e.txLog) - 1; i >= 0; i-- {
  1747. entry := e.txLog[i]
  1748. if err := e.undoOperation(entry); err != nil {
  1749. // Log error but continue with rollback
  1750. continue
  1751. }
  1752. }
  1753. // Clear transaction state
  1754. e.inTransaction = false
  1755. e.savepoints = nil
  1756. e.txLog = nil
  1757. result := NewResult("ROLLBACK")
  1758. return result, nil
  1759. }
  1760. // executeSavepoint creates a savepoint.
  1761. func (e *Executor) executeSavepoint(stmt *parser.SavepointStmt) (*Result, error) {
  1762. if !e.inTransaction {
  1763. // SQLite allows SAVEPOINT outside transaction (starts implicit transaction)
  1764. e.inTransaction = true
  1765. e.txLog = nil
  1766. }
  1767. // Add savepoint marker
  1768. e.savepoints = append(e.savepoints, stmt.Name)
  1769. result := NewResult("SAVEPOINT")
  1770. return result, nil
  1771. }
  1772. // executeRelease releases a savepoint.
  1773. func (e *Executor) executeRelease(stmt *parser.ReleaseStmt) (*Result, error) {
  1774. if !e.inTransaction {
  1775. return nil, fmt.Errorf("cannot release savepoint: no transaction in progress")
  1776. }
  1777. // Find and remove the savepoint
  1778. found := false
  1779. for i := len(e.savepoints) - 1; i >= 0; i-- {
  1780. if e.savepoints[i] == stmt.Name {
  1781. e.savepoints = e.savepoints[:i]
  1782. found = true
  1783. break
  1784. }
  1785. }
  1786. if !found {
  1787. return nil, fmt.Errorf("no such savepoint: %s", stmt.Name)
  1788. }
  1789. result := NewResult("RELEASE")
  1790. return result, nil
  1791. }
  1792. // executeAttach attaches a database.
  1793. func (e *Executor) executeAttach(stmt *parser.AttachStmt) (*Result, error) {
  1794. // Check if alias already exists
  1795. if _, exists := e.attachedDatabases[stmt.Alias]; exists {
  1796. return nil, fmt.Errorf("database alias already exists: %s", stmt.Alias)
  1797. }
  1798. // Reserved alias check
  1799. if strings.EqualFold(stmt.Alias, "temp") || strings.EqualFold(stmt.Alias, "temporary") {
  1800. return nil, fmt.Errorf("reserved database alias: %s", stmt.Alias)
  1801. }
  1802. // Get the pool from the main schema manager
  1803. pool := e.schema.GetPool()
  1804. // Create new schema and table managers for the attached database
  1805. // In PizzaKV, each database is just a different namespace/prefix
  1806. schema := storage.NewSchemaManager(pool, stmt.FilePath)
  1807. table := storage.NewTableManager(pool, schema, stmt.FilePath)
  1808. // Register the database connection
  1809. e.attachedDatabases[stmt.Alias] = &DatabaseConnection{
  1810. Alias: stmt.Alias,
  1811. Path: stmt.FilePath,
  1812. Schema: schema,
  1813. Table: table,
  1814. }
  1815. // Sync the catalog with the attached database's tables
  1816. tables, _ := schema.ListTables()
  1817. for _, tableName := range tables {
  1818. tSchema, err := schema.GetSchema(tableName)
  1819. if err != nil {
  1820. continue
  1821. }
  1822. // Add with database prefix
  1823. tableInfo := tSchema.ToAnalyzerTableInfo()
  1824. tableInfo.Name = stmt.Alias + "." + tableInfo.Name
  1825. e.catalog.CreateTable(tableInfo)
  1826. }
  1827. result := NewResult("ATTACH")
  1828. return result, nil
  1829. }
  1830. // executeDetach detaches a database.
  1831. func (e *Executor) executeDetach(stmt *parser.DetachStmt) (*Result, error) {
  1832. // Cannot detach main database
  1833. if strings.EqualFold(stmt.Alias, "main") {
  1834. return nil, fmt.Errorf("cannot detach main database")
  1835. }
  1836. // Check if database exists
  1837. if _, exists := e.attachedDatabases[stmt.Alias]; !exists {
  1838. return nil, fmt.Errorf("no such database: %s", stmt.Alias)
  1839. }
  1840. // Remove from attached databases
  1841. delete(e.attachedDatabases, stmt.Alias)
  1842. // Note: We don't remove from catalog as that would be more complex
  1843. // In a production system, we'd need to track which tables belong to which database
  1844. result := NewResult("DETACH")
  1845. return result, nil
  1846. }
  1847. // rollbackToSavepoint rolls back to a specific savepoint.
  1848. func (e *Executor) rollbackToSavepoint(name string) (*Result, error) {
  1849. // Find savepoint index
  1850. savepointIdx := -1
  1851. for i := len(e.savepoints) - 1; i >= 0; i-- {
  1852. if e.savepoints[i] == name {
  1853. savepointIdx = i
  1854. break
  1855. }
  1856. }
  1857. if savepointIdx == -1 {
  1858. return nil, fmt.Errorf("no such savepoint: %s", name)
  1859. }
  1860. // Count operations to undo (operations after the savepoint)
  1861. // For simplicity, we track savepoint positions by counting log entries
  1862. // In a real implementation, we'd track log positions per savepoint
  1863. // Undo operations in reverse order
  1864. for i := len(e.txLog) - 1; i >= 0; i-- {
  1865. entry := e.txLog[i]
  1866. if err := e.undoOperation(entry); err != nil {
  1867. continue
  1868. }
  1869. }
  1870. // Remove savepoints after the target
  1871. e.savepoints = e.savepoints[:savepointIdx+1]
  1872. result := NewResult("ROLLBACK")
  1873. return result, nil
  1874. }
  1875. // undoOperation reverses a single operation.
  1876. func (e *Executor) undoOperation(entry txLogEntry) error {
  1877. switch entry.operation {
  1878. case "INSERT":
  1879. // Delete the inserted row
  1880. _, err := e.table.Delete(entry.table, func(r storage.Row) bool {
  1881. // Match by primary key stored in entry.key
  1882. pk := e.getPrimaryKey(entry.table)
  1883. if pk == "" {
  1884. return false
  1885. }
  1886. return fmt.Sprintf("%v", r[pk]) == entry.key
  1887. })
  1888. return err
  1889. case "DELETE":
  1890. // Re-insert the deleted row
  1891. if entry.oldData != nil {
  1892. return e.table.Insert(entry.table, entry.oldData)
  1893. }
  1894. case "UPDATE":
  1895. // Restore the old data
  1896. if entry.oldData != nil {
  1897. pk := e.getPrimaryKey(entry.table)
  1898. if pk != "" {
  1899. // Delete current row and insert old data
  1900. e.table.Delete(entry.table, func(r storage.Row) bool {
  1901. return fmt.Sprintf("%v", r[pk]) == entry.key
  1902. })
  1903. return e.table.Insert(entry.table, entry.oldData)
  1904. }
  1905. }
  1906. }
  1907. return nil
  1908. }
  1909. // getPrimaryKey returns the primary key column name for a table.
  1910. func (e *Executor) getPrimaryKey(tableName string) string {
  1911. schema, err := e.schema.GetSchema(tableName)
  1912. if err != nil {
  1913. return ""
  1914. }
  1915. return schema.PrimaryKey
  1916. }
  1917. // extractIndexableCondition extracts column name and value from a simple equality condition.
  1918. // Returns (column, value, true) if the expression is column = literal.
  1919. func (e *Executor) extractIndexableCondition(expr parser.Expr) (string, interface{}, bool) {
  1920. binExpr, ok := expr.(*parser.BinaryExpr)
  1921. if !ok {
  1922. return "", nil, false
  1923. }
  1924. // Only handle equality for now
  1925. if binExpr.Op != lexer.TokenEq {
  1926. return "", nil, false
  1927. }
  1928. // Check for column = literal pattern
  1929. colRef, leftIsCol := binExpr.Left.(*parser.ColumnRef)
  1930. litExpr, rightIsLit := binExpr.Right.(*parser.LiteralExpr)
  1931. if leftIsCol && rightIsLit {
  1932. val, _ := e.evalLiteral(litExpr)
  1933. return colRef.Column, val, true
  1934. }
  1935. // Check for literal = column pattern
  1936. litExpr, leftIsLit := binExpr.Left.(*parser.LiteralExpr)
  1937. colRef, rightIsCol := binExpr.Right.(*parser.ColumnRef)
  1938. if leftIsLit && rightIsCol {
  1939. val, _ := e.evalLiteral(litExpr)
  1940. return colRef.Column, val, true
  1941. }
  1942. return "", nil, false
  1943. }
  1944. // executePragma executes a PRAGMA statement.
  1945. func (e *Executor) executePragma(stmt *parser.PragmaStmt) (*Result, error) {
  1946. switch stmt.Name {
  1947. case "table_info":
  1948. return e.pragmaTableInfo(stmt.Arg)
  1949. case "table_list":
  1950. return e.pragmaTableList()
  1951. case "database_list":
  1952. return e.pragmaDatabaseList()
  1953. case "version":
  1954. return e.pragmaVersion()
  1955. default:
  1956. return nil, fmt.Errorf("unknown pragma: %s", stmt.Name)
  1957. }
  1958. }
  1959. // pragmaTableInfo returns column information for a table.
  1960. func (e *Executor) pragmaTableInfo(tableName string) (*Result, error) {
  1961. if tableName == "" {
  1962. return nil, fmt.Errorf("table_info requires a table name")
  1963. }
  1964. schema, err := e.schema.GetSchema(tableName)
  1965. if err != nil {
  1966. return nil, err
  1967. }
  1968. result := NewResult("PRAGMA")
  1969. result.AddColumn("cid")
  1970. result.AddColumn("name")
  1971. result.AddColumn("type")
  1972. result.AddColumn("notnull")
  1973. result.AddColumn("dflt_value")
  1974. result.AddColumn("pk")
  1975. for i, col := range schema.Columns {
  1976. notnull := 0
  1977. if !col.Nullable {
  1978. notnull = 1
  1979. }
  1980. pk := 0
  1981. if col.PrimaryKey {
  1982. pk = 1
  1983. }
  1984. result.AddRow(int64(i), col.Name, col.Type, int64(notnull), col.Default, int64(pk))
  1985. }
  1986. return result, nil
  1987. }
  1988. // pragmaTableList returns a list of all tables.
  1989. func (e *Executor) pragmaTableList() (*Result, error) {
  1990. tables, err := e.schema.ListTables()
  1991. if err != nil {
  1992. return nil, err
  1993. }
  1994. result := NewResult("PRAGMA")
  1995. result.AddColumn("schema")
  1996. result.AddColumn("name")
  1997. result.AddColumn("type")
  1998. for _, t := range tables {
  1999. result.AddRow("main", t, "table")
  2000. }
  2001. return result, nil
  2002. }
  2003. // pragmaDatabaseList returns a list of databases.
  2004. func (e *Executor) pragmaDatabaseList() (*Result, error) {
  2005. result := NewResult("PRAGMA")
  2006. result.AddColumn("seq")
  2007. result.AddColumn("name")
  2008. result.AddColumn("file")
  2009. // We only have one database
  2010. result.AddRow(int64(0), "main", "")
  2011. return result, nil
  2012. }
  2013. // pragmaVersion returns the PizzaSQL version.
  2014. func (e *Executor) pragmaVersion() (*Result, error) {
  2015. result := NewResult("PRAGMA")
  2016. result.AddColumn("version")
  2017. result.AddRow("PizzaSQL 1.0.0")
  2018. return result, nil
  2019. }
  2020. // executeExplain executes an EXPLAIN statement.
  2021. func (e *Executor) executeExplain(stmt *parser.ExplainStmt) (*Result, error) {
  2022. result := NewResult("EXPLAIN")
  2023. if stmt.QueryPlan {
  2024. // EXPLAIN QUERY PLAN format
  2025. result.AddColumn("id")
  2026. result.AddColumn("parent")
  2027. result.AddColumn("notused")
  2028. result.AddColumn("detail")
  2029. plan := e.generateQueryPlan(stmt.Statement)
  2030. for i, step := range plan {
  2031. result.AddRow(int64(i), int64(0), int64(0), step)
  2032. }
  2033. } else {
  2034. // Simple EXPLAIN format
  2035. result.AddColumn("addr")
  2036. result.AddColumn("opcode")
  2037. result.AddColumn("p1")
  2038. result.AddColumn("p2")
  2039. result.AddColumn("p3")
  2040. result.AddColumn("p4")
  2041. result.AddColumn("p5")
  2042. result.AddColumn("comment")
  2043. ops := e.generateOpcodes(stmt.Statement)
  2044. for i, op := range ops {
  2045. result.AddRow(int64(i), op, int64(0), int64(0), int64(0), "", int64(0), "")
  2046. }
  2047. }
  2048. return result, nil
  2049. }
  2050. // generateQueryPlan generates a simple query plan description.
  2051. func (e *Executor) generateQueryPlan(stmt parser.Statement) []string {
  2052. var plan []string
  2053. switch s := stmt.(type) {
  2054. case *parser.SelectStmt:
  2055. if len(s.From) > 0 {
  2056. plan = append(plan, fmt.Sprintf("SCAN TABLE %s", s.From[0].Name))
  2057. if s.Where != nil {
  2058. plan = append(plan, "FILTER")
  2059. }
  2060. if len(s.OrderBy) > 0 {
  2061. plan = append(plan, "SORT")
  2062. }
  2063. if s.Limit != nil {
  2064. plan = append(plan, "LIMIT")
  2065. }
  2066. } else {
  2067. plan = append(plan, "SCALAR EXPRESSION")
  2068. }
  2069. case *parser.InsertStmt:
  2070. plan = append(plan, fmt.Sprintf("INSERT INTO %s", s.Table.Name))
  2071. case *parser.UpdateStmt:
  2072. plan = append(plan, fmt.Sprintf("SCAN TABLE %s", s.Table.Name))
  2073. plan = append(plan, "UPDATE")
  2074. case *parser.DeleteStmt:
  2075. plan = append(plan, fmt.Sprintf("SCAN TABLE %s", s.Table.Name))
  2076. plan = append(plan, "DELETE")
  2077. default:
  2078. plan = append(plan, "EXECUTE")
  2079. }
  2080. return plan
  2081. }
  2082. // generateOpcodes generates simplified opcodes for EXPLAIN.
  2083. func (e *Executor) generateOpcodes(stmt parser.Statement) []string {
  2084. var ops []string
  2085. switch s := stmt.(type) {
  2086. case *parser.SelectStmt:
  2087. ops = append(ops, "Init")
  2088. if len(s.From) > 0 {
  2089. ops = append(ops, "OpenRead")
  2090. ops = append(ops, "Rewind")
  2091. ops = append(ops, "Column")
  2092. ops = append(ops, "ResultRow")
  2093. ops = append(ops, "Next")
  2094. ops = append(ops, "Close")
  2095. } else {
  2096. ops = append(ops, "Integer")
  2097. ops = append(ops, "ResultRow")
  2098. }
  2099. ops = append(ops, "Halt")
  2100. case *parser.InsertStmt:
  2101. ops = append(ops, "Init")
  2102. ops = append(ops, "OpenWrite")
  2103. ops = append(ops, "NewRowid")
  2104. ops = append(ops, "Insert")
  2105. ops = append(ops, "Close")
  2106. ops = append(ops, "Halt")
  2107. case *parser.UpdateStmt:
  2108. ops = append(ops, "Init")
  2109. ops = append(ops, "OpenWrite")
  2110. ops = append(ops, "Rewind")
  2111. ops = append(ops, "Column")
  2112. ops = append(ops, "Update")
  2113. ops = append(ops, "Next")
  2114. ops = append(ops, "Close")
  2115. ops = append(ops, "Halt")
  2116. case *parser.DeleteStmt:
  2117. ops = append(ops, "Init")
  2118. ops = append(ops, "OpenWrite")
  2119. ops = append(ops, "Rewind")
  2120. ops = append(ops, "Delete")
  2121. ops = append(ops, "Next")
  2122. ops = append(ops, "Close")
  2123. ops = append(ops, "Halt")
  2124. default:
  2125. ops = append(ops, "Init")
  2126. ops = append(ops, "Halt")
  2127. }
  2128. return ops
  2129. }
  2130. // evalExpr evaluates an expression.
  2131. func (e *Executor) evalExpr(expr parser.Expr, row storage.Row) (interface{}, error) {
  2132. switch ex := expr.(type) {
  2133. case *parser.LiteralExpr:
  2134. return e.evalLiteral(ex)
  2135. case *parser.ColumnRef:
  2136. return e.evalColumnRef(ex, row)
  2137. case *parser.BinaryExpr:
  2138. return e.evalBinaryExpr(ex, row)
  2139. case *parser.UnaryExpr:
  2140. return e.evalUnaryExpr(ex, row)
  2141. case *parser.FunctionCall:
  2142. return e.evalFunctionCall(ex, row)
  2143. case *parser.ParenExpr:
  2144. return e.evalExpr(ex.Expr, row)
  2145. case *parser.CaseExpr:
  2146. return e.evalCaseExpr(ex, row)
  2147. case *parser.InExpr:
  2148. return e.evalInExpr(ex, row)
  2149. case *parser.BetweenExpr:
  2150. return e.evalBetweenExpr(ex, row)
  2151. case *parser.LikeExpr:
  2152. return e.evalLikeExpr(ex, row)
  2153. case *parser.IsNullExpr:
  2154. return e.evalIsNullExpr(ex, row)
  2155. case *parser.CastExpr:
  2156. return e.evalCastExpr(ex, row)
  2157. case *parser.SubqueryExpr:
  2158. return e.evalSubqueryExpr(ex, row)
  2159. case *parser.ExistsExpr:
  2160. return e.evalExistsExpr(ex, row)
  2161. default:
  2162. return nil, fmt.Errorf("unsupported expression type: %T", expr)
  2163. }
  2164. }
  2165. func (e *Executor) evalLiteral(lit *parser.LiteralExpr) (interface{}, error) {
  2166. switch lit.Type {
  2167. case lexer.TokenNumber:
  2168. // Check for scientific notation (e.g., 1e+06) or decimal point
  2169. if strings.Contains(lit.Value, ".") || strings.ContainsAny(lit.Value, "eE") {
  2170. f, err := strconv.ParseFloat(lit.Value, 64)
  2171. if err != nil {
  2172. return nil, err
  2173. }
  2174. // If it's a whole number (no fractional part), return as int64
  2175. if f == float64(int64(f)) {
  2176. return int64(f), nil
  2177. }
  2178. return f, nil
  2179. }
  2180. return strconv.ParseInt(lit.Value, 10, 64)
  2181. case lexer.TokenString:
  2182. return lit.Value, nil
  2183. case lexer.TokenNULL:
  2184. return nil, nil
  2185. case lexer.TokenTRUE:
  2186. return true, nil
  2187. case lexer.TokenFALSE:
  2188. return false, nil
  2189. default:
  2190. return lit.Value, nil
  2191. }
  2192. }
  2193. func (e *Executor) evalColumnRef(ref *parser.ColumnRef, row storage.Row) (interface{}, error) {
  2194. if row == nil {
  2195. return nil, fmt.Errorf("no row context for column: %s", ref.Column)
  2196. }
  2197. // Check for ROWID aliases (rowid, oid, _rowid_)
  2198. if storage.IsRowIDColumn(ref.Column) {
  2199. if val, ok := row["_rowid_"]; ok {
  2200. return val, nil
  2201. }
  2202. return nil, nil
  2203. }
  2204. // For qualified column references (table.column):
  2205. //
  2206. // Resolution order:
  2207. // 1. Exact qualified key in outer row ("t1.b" → outer)
  2208. // 2. Case-insensitive qualified in outer row
  2209. // 3. Exact qualified key in current row ("x.b" → inner alias)
  2210. // 4. Case-insensitive qualified in current row
  2211. // 5. Unqualified in outer row — only reached when qualified lookup in current
  2212. // row failed, meaning the qualifier refers to an outer table not the inner
  2213. // alias (e.g. "t1.b" in a subquery "FROM t1 AS x" resolves here).
  2214. // 6. Unqualified in current row (last resort)
  2215. if ref.Table != "" {
  2216. if e.outerRow != nil {
  2217. // Step 1-2: qualified lookup in outer row
  2218. if val, ok := e.outerRow[ref.Table+"."+ref.Column]; ok {
  2219. return val, nil
  2220. }
  2221. for k, v := range e.outerRow {
  2222. if strings.EqualFold(k, ref.Table+"."+ref.Column) {
  2223. return v, nil
  2224. }
  2225. }
  2226. }
  2227. // Step 3-4: qualified lookup in current row
  2228. if val, ok := row[ref.Table+"."+ref.Column]; ok {
  2229. return val, nil
  2230. }
  2231. for k, v := range row {
  2232. if strings.EqualFold(k, ref.Table+"."+ref.Column) {
  2233. return v, nil
  2234. }
  2235. }
  2236. // Step 5: qualified lookup failed in current row — try outer row unqualified.
  2237. // This handles correlated subqueries where the qualifier names an outer table
  2238. // (e.g. "t1.b" when the inner FROM is "t1 AS x", so current row has "x.b"
  2239. // but no "t1.b").
  2240. if e.outerRow != nil {
  2241. if val, ok := e.outerRow[ref.Column]; ok {
  2242. return val, nil
  2243. }
  2244. for k, v := range e.outerRow {
  2245. if strings.EqualFold(k, ref.Column) {
  2246. return v, nil
  2247. }
  2248. }
  2249. }
  2250. }
  2251. // Step 6: unqualified fallback in current row (handles unqualified refs and
  2252. // single-table queries like "SELECT t1.a FROM t1" where rows have plain keys).
  2253. if val, ok := row[ref.Column]; ok {
  2254. return val, nil
  2255. }
  2256. for k, v := range row {
  2257. if strings.EqualFold(k, ref.Column) {
  2258. return v, nil
  2259. }
  2260. }
  2261. // For unqualified refs with an outer row context (ref.Table == "").
  2262. if e.outerRow != nil && ref.Table == "" {
  2263. if val, ok := e.outerRow[ref.Column]; ok {
  2264. return val, nil
  2265. }
  2266. for k, v := range e.outerRow {
  2267. if strings.EqualFold(k, ref.Column) {
  2268. return v, nil
  2269. }
  2270. }
  2271. }
  2272. return nil, nil // Column not found, return NULL
  2273. }
  2274. func (e *Executor) evalBinaryExpr(expr *parser.BinaryExpr, row storage.Row) (interface{}, error) {
  2275. left, err := e.evalExpr(expr.Left, row)
  2276. if err != nil {
  2277. return nil, err
  2278. }
  2279. right, err := e.evalExpr(expr.Right, row)
  2280. if err != nil {
  2281. return nil, err
  2282. }
  2283. switch expr.Op {
  2284. case lexer.TokenPlus:
  2285. if left == nil || right == nil {
  2286. return nil, nil
  2287. }
  2288. return toFloat(left) + toFloat(right), nil
  2289. case lexer.TokenMinus:
  2290. if left == nil || right == nil {
  2291. return nil, nil
  2292. }
  2293. return toFloat(left) - toFloat(right), nil
  2294. case lexer.TokenStar:
  2295. if left == nil || right == nil {
  2296. return nil, nil
  2297. }
  2298. return toFloat(left) * toFloat(right), nil
  2299. case lexer.TokenSlash:
  2300. if left == nil || right == nil {
  2301. return nil, nil
  2302. }
  2303. r := toFloat(right)
  2304. if r == 0 {
  2305. return nil, nil // Division by zero returns NULL
  2306. }
  2307. return toFloat(left) / r, nil
  2308. case lexer.TokenPercent:
  2309. if left == nil || right == nil {
  2310. return nil, nil
  2311. }
  2312. return int64(toFloat(left)) % int64(toFloat(right)), nil
  2313. case lexer.TokenEq:
  2314. if left == nil || right == nil {
  2315. return nil, nil
  2316. }
  2317. return compare(left, right) == 0, nil
  2318. case lexer.TokenNeq:
  2319. if left == nil || right == nil {
  2320. return nil, nil
  2321. }
  2322. return compare(left, right) != 0, nil
  2323. case lexer.TokenLt:
  2324. if left == nil || right == nil {
  2325. return nil, nil
  2326. }
  2327. return compare(left, right) < 0, nil
  2328. case lexer.TokenLte:
  2329. if left == nil || right == nil {
  2330. return nil, nil
  2331. }
  2332. return compare(left, right) <= 0, nil
  2333. case lexer.TokenGt:
  2334. if left == nil || right == nil {
  2335. return nil, nil
  2336. }
  2337. return compare(left, right) > 0, nil
  2338. case lexer.TokenGte:
  2339. if left == nil || right == nil {
  2340. return nil, nil
  2341. }
  2342. return compare(left, right) >= 0, nil
  2343. case lexer.TokenAND:
  2344. lb, rb := toBool(left), toBool(right)
  2345. if !lb || !rb {
  2346. return false, nil
  2347. }
  2348. if left == nil || right == nil {
  2349. return nil, nil
  2350. }
  2351. return true, nil
  2352. case lexer.TokenOR:
  2353. lb, rb := toBool(left), toBool(right)
  2354. if lb || rb {
  2355. return true, nil
  2356. }
  2357. if left == nil || right == nil {
  2358. return nil, nil
  2359. }
  2360. return false, nil
  2361. case lexer.TokenConcat:
  2362. return toString(left) + toString(right), nil
  2363. default:
  2364. return nil, fmt.Errorf("unsupported operator: %v", expr.Op)
  2365. }
  2366. }
  2367. func (e *Executor) evalUnaryExpr(expr *parser.UnaryExpr, row storage.Row) (interface{}, error) {
  2368. val, err := e.evalExpr(expr.Operand, row)
  2369. if err != nil {
  2370. return nil, err
  2371. }
  2372. switch expr.Op {
  2373. case lexer.TokenMinus:
  2374. if val == nil {
  2375. return nil, nil
  2376. }
  2377. return -toFloat(val), nil
  2378. case lexer.TokenPlus:
  2379. if val == nil {
  2380. return nil, nil
  2381. }
  2382. return toFloat(val), nil
  2383. case lexer.TokenNOT:
  2384. if val == nil {
  2385. return nil, nil // NOT NULL = NULL
  2386. }
  2387. return !toBool(val), nil
  2388. default:
  2389. return val, nil
  2390. }
  2391. }
  2392. func (e *Executor) evalFunctionCall(fn *parser.FunctionCall, row storage.Row) (interface{}, error) {
  2393. name := strings.ToUpper(fn.Name)
  2394. // Evaluate arguments
  2395. args := make([]interface{}, len(fn.Args))
  2396. for i, arg := range fn.Args {
  2397. val, err := e.evalExpr(arg, row)
  2398. if err != nil {
  2399. return nil, err
  2400. }
  2401. args[i] = val
  2402. }
  2403. switch name {
  2404. case "UPPER":
  2405. if len(args) > 0 {
  2406. if args[0] == nil {
  2407. return nil, nil // NULL propagation
  2408. }
  2409. return strings.ToUpper(toString(args[0])), nil
  2410. }
  2411. case "LOWER":
  2412. if len(args) > 0 {
  2413. if args[0] == nil {
  2414. return nil, nil // NULL propagation
  2415. }
  2416. return strings.ToLower(toString(args[0])), nil
  2417. }
  2418. case "LENGTH":
  2419. if len(args) > 0 {
  2420. if args[0] == nil {
  2421. return nil, nil // NULL propagation
  2422. }
  2423. return int64(len(toString(args[0]))), nil
  2424. }
  2425. case "ABS":
  2426. if len(args) > 0 {
  2427. if args[0] == nil {
  2428. return nil, nil
  2429. }
  2430. v := toFloat(args[0])
  2431. if v < 0 {
  2432. return -v, nil
  2433. }
  2434. return v, nil
  2435. }
  2436. case "COALESCE":
  2437. for _, arg := range args {
  2438. if arg != nil {
  2439. return arg, nil
  2440. }
  2441. }
  2442. return nil, nil
  2443. case "NULLIF":
  2444. if len(args) >= 2 && compare(args[0], args[1]) == 0 {
  2445. return nil, nil
  2446. }
  2447. if len(args) > 0 {
  2448. return args[0], nil
  2449. }
  2450. case "IFNULL":
  2451. if len(args) >= 2 {
  2452. if args[0] == nil {
  2453. return args[1], nil
  2454. }
  2455. return args[0], nil
  2456. }
  2457. case "TYPEOF":
  2458. if len(args) > 0 {
  2459. switch args[0].(type) {
  2460. case nil:
  2461. return "null", nil
  2462. case int64, int:
  2463. return "integer", nil
  2464. case float64:
  2465. return "real", nil
  2466. case string:
  2467. return "text", nil
  2468. case []byte:
  2469. return "blob", nil
  2470. default:
  2471. return "text", nil
  2472. }
  2473. }
  2474. case "SUBSTR", "SUBSTRING":
  2475. if len(args) >= 2 {
  2476. s := toString(args[0])
  2477. start := int(toFloat(args[1])) - 1 // SQL is 1-indexed
  2478. if start < 0 {
  2479. start = 0
  2480. }
  2481. if start >= len(s) {
  2482. return "", nil
  2483. }
  2484. if len(args) >= 3 {
  2485. length := int(toFloat(args[2]))
  2486. if start+length > len(s) {
  2487. length = len(s) - start
  2488. }
  2489. return s[start : start+length], nil
  2490. }
  2491. return s[start:], nil
  2492. }
  2493. case "TRIM":
  2494. if len(args) > 0 {
  2495. return strings.TrimSpace(toString(args[0])), nil
  2496. }
  2497. case "REPLACE":
  2498. if len(args) >= 3 {
  2499. return strings.ReplaceAll(toString(args[0]), toString(args[1]), toString(args[2])), nil
  2500. }
  2501. // Additional SQLite functions
  2502. case "PRINTF":
  2503. if len(args) > 0 {
  2504. format := toString(args[0])
  2505. fmtArgs := make([]interface{}, len(args)-1)
  2506. for i := 1; i < len(args); i++ {
  2507. fmtArgs[i-1] = args[i]
  2508. }
  2509. return fmt.Sprintf(format, fmtArgs...), nil
  2510. }
  2511. case "HEX":
  2512. if len(args) > 0 {
  2513. s := toString(args[0])
  2514. return strings.ToUpper(fmt.Sprintf("%x", []byte(s))), nil
  2515. }
  2516. case "UNHEX":
  2517. if len(args) > 0 {
  2518. s := toString(args[0])
  2519. var result []byte
  2520. for i := 0; i < len(s)-1; i += 2 {
  2521. var b byte
  2522. fmt.Sscanf(s[i:i+2], "%x", &b)
  2523. result = append(result, b)
  2524. }
  2525. return string(result), nil
  2526. }
  2527. case "RANDOM":
  2528. return rand.Int63(), nil
  2529. case "RANDOMBLOB":
  2530. if len(args) > 0 {
  2531. n := int(toFloat(args[0]))
  2532. if n <= 0 {
  2533. n = 1
  2534. }
  2535. if n > 1000000 {
  2536. n = 1000000
  2537. }
  2538. blob := make([]byte, n)
  2539. rand.Read(blob)
  2540. return string(blob), nil
  2541. }
  2542. case "ZEROBLOB":
  2543. if len(args) > 0 {
  2544. n := int(toFloat(args[0]))
  2545. if n <= 0 {
  2546. n = 1
  2547. }
  2548. if n > 1000000 {
  2549. n = 1000000
  2550. }
  2551. return string(make([]byte, n)), nil
  2552. }
  2553. case "INSTR":
  2554. if len(args) >= 2 {
  2555. s := toString(args[0])
  2556. substr := toString(args[1])
  2557. idx := strings.Index(s, substr)
  2558. if idx < 0 {
  2559. return int64(0), nil
  2560. }
  2561. return int64(idx + 1), nil // SQL is 1-indexed
  2562. }
  2563. case "GLOB":
  2564. if len(args) >= 2 {
  2565. pattern := toString(args[0])
  2566. s := toString(args[1])
  2567. return matchGlob(pattern, s), nil
  2568. }
  2569. case "ROUND":
  2570. if len(args) > 0 {
  2571. v := toFloat(args[0])
  2572. decimals := 0
  2573. if len(args) >= 2 {
  2574. decimals = int(toFloat(args[1]))
  2575. }
  2576. mult := 1.0
  2577. for i := 0; i < decimals; i++ {
  2578. mult *= 10
  2579. }
  2580. return float64(int64(v*mult+0.5)) / mult, nil
  2581. }
  2582. case "MAX":
  2583. if len(args) > 0 {
  2584. max := args[0]
  2585. for _, arg := range args[1:] {
  2586. if compare(arg, max) > 0 {
  2587. max = arg
  2588. }
  2589. }
  2590. return max, nil
  2591. }
  2592. case "MIN":
  2593. if len(args) > 0 {
  2594. min := args[0]
  2595. for _, arg := range args[1:] {
  2596. if compare(arg, min) < 0 {
  2597. min = arg
  2598. }
  2599. }
  2600. return min, nil
  2601. }
  2602. case "CONCAT":
  2603. var result strings.Builder
  2604. for _, arg := range args {
  2605. result.WriteString(toString(arg))
  2606. }
  2607. return result.String(), nil
  2608. }
  2609. return nil, nil
  2610. }
  2611. func (e *Executor) evalCaseExpr(expr *parser.CaseExpr, row storage.Row) (interface{}, error) {
  2612. var operand interface{}
  2613. if expr.Operand != nil {
  2614. var err error
  2615. operand, err = e.evalExpr(expr.Operand, row)
  2616. if err != nil {
  2617. return nil, err
  2618. }
  2619. }
  2620. for _, when := range expr.Whens {
  2621. cond, err := e.evalExpr(when.Condition, row)
  2622. if err != nil {
  2623. return nil, err
  2624. }
  2625. var match bool
  2626. if expr.Operand != nil {
  2627. // Simple CASE: CASE operand WHEN val THEN ... — NULL operand matches nothing
  2628. if operand == nil {
  2629. continue
  2630. }
  2631. match = compare(operand, cond) == 0
  2632. } else {
  2633. // Searched CASE: CASE WHEN cond THEN ... — NULL condition is falsy
  2634. match = toBool(cond)
  2635. }
  2636. if match {
  2637. return e.evalExpr(when.Result, row)
  2638. }
  2639. }
  2640. if expr.Else != nil {
  2641. return e.evalExpr(expr.Else, row)
  2642. }
  2643. return nil, nil
  2644. }
  2645. func (e *Executor) evalInExpr(expr *parser.InExpr, row storage.Row) (interface{}, error) {
  2646. left, err := e.evalExpr(expr.Left, row)
  2647. if err != nil {
  2648. return nil, err
  2649. }
  2650. // Handle subquery: IN (SELECT ...)
  2651. if expr.Subquery != nil {
  2652. var result *Result
  2653. var err error
  2654. // Cache non-correlated subquery results for the duration of this query.
  2655. // Safe when outerRow is nil (no outer context that the subquery could reference).
  2656. if e.subqueryCache != nil && e.outerRow == nil {
  2657. if cached, ok := e.subqueryCache[expr.Subquery]; ok {
  2658. result = cached
  2659. } else {
  2660. result, err = e.executeSelect(expr.Subquery)
  2661. if err == nil {
  2662. e.subqueryCache[expr.Subquery] = result
  2663. }
  2664. }
  2665. } else {
  2666. result, err = e.executeSelect(expr.Subquery)
  2667. }
  2668. if err != nil {
  2669. return nil, fmt.Errorf("IN subquery error: %w", err)
  2670. }
  2671. if len(result.Columns) != 1 {
  2672. return nil, fmt.Errorf("subquery in IN must return exactly one column")
  2673. }
  2674. // SQL three-valued logic: if left is NULL → NULL; if any match → true; if any NULL → NULL; else false.
  2675. if left == nil {
  2676. return nil, nil
  2677. }
  2678. sawNull := false
  2679. for _, resultRow := range result.Rows {
  2680. if len(resultRow) == 0 {
  2681. continue
  2682. }
  2683. v := resultRow[0]
  2684. if v == nil {
  2685. sawNull = true
  2686. continue
  2687. }
  2688. if compare(left, v) == 0 {
  2689. if expr.Not {
  2690. return false, nil
  2691. }
  2692. return true, nil
  2693. }
  2694. }
  2695. if sawNull {
  2696. return nil, nil
  2697. }
  2698. if expr.Not {
  2699. return true, nil
  2700. }
  2701. return false, nil
  2702. }
  2703. // Handle value list: IN (1, 2, 3).
  2704. // Empty list: always FALSE (IN) / TRUE (NOT IN), even for NULL.
  2705. if len(expr.Values) == 0 {
  2706. return expr.Not, nil
  2707. }
  2708. // SQL three-valued logic: if left is NULL → NULL; if any match → true/false;
  2709. // if list contains NULL and no match → NULL.
  2710. if left == nil {
  2711. return nil, nil
  2712. }
  2713. sawNull := false
  2714. for _, val := range expr.Values {
  2715. v, err := e.evalExpr(val, row)
  2716. if err != nil {
  2717. return nil, err
  2718. }
  2719. if v == nil {
  2720. sawNull = true
  2721. continue
  2722. }
  2723. if compare(left, v) == 0 {
  2724. if expr.Not {
  2725. return false, nil
  2726. }
  2727. return true, nil
  2728. }
  2729. }
  2730. if sawNull {
  2731. return nil, nil
  2732. }
  2733. if expr.Not {
  2734. return true, nil
  2735. }
  2736. return false, nil
  2737. }
  2738. func (e *Executor) evalBetweenExpr(expr *parser.BetweenExpr, row storage.Row) (interface{}, error) {
  2739. val, err := e.evalExpr(expr.Left, row)
  2740. if err != nil {
  2741. return nil, err
  2742. }
  2743. low, err := e.evalExpr(expr.Low, row)
  2744. if err != nil {
  2745. return nil, err
  2746. }
  2747. high, err := e.evalExpr(expr.High, row)
  2748. if err != nil {
  2749. return nil, err
  2750. }
  2751. if val == nil || low == nil || high == nil {
  2752. return nil, nil
  2753. }
  2754. inRange := compare(val, low) >= 0 && compare(val, high) <= 0
  2755. if expr.Not {
  2756. return !inRange, nil
  2757. }
  2758. return inRange, nil
  2759. }
  2760. func (e *Executor) evalLikeExpr(expr *parser.LikeExpr, row storage.Row) (interface{}, error) {
  2761. val, err := e.evalExpr(expr.Left, row)
  2762. if err != nil {
  2763. return nil, err
  2764. }
  2765. pattern, err := e.evalExpr(expr.Pattern, row)
  2766. if err != nil {
  2767. return nil, err
  2768. }
  2769. s := toString(val)
  2770. p := toString(pattern)
  2771. // Convert SQL LIKE pattern to simple matching
  2772. // % matches any sequence, _ matches single character
  2773. matched := matchLike(s, p)
  2774. if expr.Not {
  2775. return !matched, nil
  2776. }
  2777. return matched, nil
  2778. }
  2779. func (e *Executor) evalIsNullExpr(expr *parser.IsNullExpr, row storage.Row) (interface{}, error) {
  2780. val, err := e.evalExpr(expr.Left, row)
  2781. if err != nil {
  2782. return nil, err
  2783. }
  2784. isNull := val == nil
  2785. if expr.Not {
  2786. return !isNull, nil
  2787. }
  2788. return isNull, nil
  2789. }
  2790. func (e *Executor) evalCastExpr(expr *parser.CastExpr, row storage.Row) (interface{}, error) {
  2791. val, err := e.evalExpr(expr.Expr, row)
  2792. if err != nil {
  2793. return nil, err
  2794. }
  2795. if val == nil {
  2796. return nil, nil // CAST(NULL AS any) = NULL
  2797. }
  2798. typeName := strings.ToUpper(expr.Type.Name)
  2799. switch {
  2800. case strings.Contains(typeName, "INT"):
  2801. return int64(toFloat(val)), nil
  2802. case strings.Contains(typeName, "REAL"), strings.Contains(typeName, "FLOAT"), strings.Contains(typeName, "DOUBLE"):
  2803. return toFloat(val), nil
  2804. case strings.Contains(typeName, "TEXT"), strings.Contains(typeName, "CHAR"):
  2805. return toString(val), nil
  2806. default:
  2807. return val, nil
  2808. }
  2809. }
  2810. // evalSubqueryExpr executes a scalar subquery and returns its value.
  2811. // A scalar subquery must return exactly one column. It returns:
  2812. // - The single value if the subquery returns one row
  2813. // - NULL if the subquery returns no rows
  2814. // - Error if the subquery returns more than one row (for strict SQL compliance)
  2815. func (e *Executor) evalSubqueryExpr(expr *parser.SubqueryExpr, row storage.Row) (interface{}, error) {
  2816. // Save and set outer row context for correlated subqueries
  2817. savedOuter := e.outerRow
  2818. e.outerRow = row
  2819. defer func() { e.outerRow = savedOuter }()
  2820. // Execute the subquery
  2821. result, err := e.executeSelect(expr.Query)
  2822. if err != nil {
  2823. return nil, fmt.Errorf("subquery error: %w", err)
  2824. }
  2825. // Check for empty result
  2826. if result.RowCount == 0 {
  2827. return nil, nil // Return NULL for empty subquery
  2828. }
  2829. // Check column count
  2830. if len(result.Columns) == 0 {
  2831. return nil, fmt.Errorf("subquery must return at least one column")
  2832. }
  2833. // For scalar subquery, return first column of first row
  2834. // Note: Strict SQL would error if more than one row is returned
  2835. // but we follow SQLite behavior which just returns the first value
  2836. if len(result.Rows) > 0 && len(result.Rows[0]) > 0 {
  2837. return result.Rows[0][0], nil
  2838. }
  2839. return nil, nil
  2840. }
  2841. // evalExistsExpr evaluates an EXISTS expression.
  2842. // Returns true if the subquery returns at least one row, false otherwise.
  2843. func (e *Executor) evalExistsExpr(expr *parser.ExistsExpr, row storage.Row) (interface{}, error) {
  2844. // Save and set outer row context for correlated subqueries
  2845. savedOuter := e.outerRow
  2846. e.outerRow = row
  2847. defer func() { e.outerRow = savedOuter }()
  2848. // Execute the subquery
  2849. result, err := e.executeSelect(expr.Subquery)
  2850. if err != nil {
  2851. return nil, fmt.Errorf("EXISTS subquery error: %w", err)
  2852. }
  2853. // EXISTS returns true if any rows are returned
  2854. return len(result.Rows) > 0, nil
  2855. }
  2856. // evalAggregateExpr evaluates an aggregate expression over multiple rows.
  2857. func (e *Executor) evalAggregateExpr(expr parser.Expr, rows []storage.Row) (interface{}, error) {
  2858. fn, ok := expr.(*parser.FunctionCall)
  2859. if !ok {
  2860. // Not a function call - could be a binary expression with aggregates inside
  2861. // Evaluate it with the aggregate evaluation context
  2862. return e.evalExprWithAggregates(expr, rows)
  2863. }
  2864. name := strings.ToUpper(fn.Name)
  2865. switch name {
  2866. case "COUNT":
  2867. if fn.Star {
  2868. return int64(len(rows)), nil
  2869. }
  2870. if fn.Distinct {
  2871. seen := make(map[interface{}]struct{})
  2872. for _, row := range rows {
  2873. if len(fn.Args) > 0 {
  2874. val, _ := e.evalExpr(fn.Args[0], row)
  2875. if val != nil {
  2876. seen[val] = struct{}{}
  2877. }
  2878. }
  2879. }
  2880. return int64(len(seen)), nil
  2881. }
  2882. count := int64(0)
  2883. for _, row := range rows {
  2884. if len(fn.Args) > 0 {
  2885. val, _ := e.evalExpr(fn.Args[0], row)
  2886. if val != nil {
  2887. count++
  2888. }
  2889. }
  2890. }
  2891. return count, nil
  2892. case "SUM":
  2893. var sum float64
  2894. for _, row := range rows {
  2895. if len(fn.Args) > 0 {
  2896. val, _ := e.evalExpr(fn.Args[0], row)
  2897. if val != nil {
  2898. sum += toFloat(val)
  2899. }
  2900. }
  2901. }
  2902. return sum, nil
  2903. case "AVG":
  2904. var sum float64
  2905. count := 0
  2906. for _, row := range rows {
  2907. if len(fn.Args) > 0 {
  2908. val, _ := e.evalExpr(fn.Args[0], row)
  2909. if val != nil {
  2910. sum += toFloat(val)
  2911. count++
  2912. }
  2913. }
  2914. }
  2915. if count == 0 {
  2916. return nil, nil
  2917. }
  2918. return sum / float64(count), nil
  2919. case "MIN":
  2920. var min interface{}
  2921. for _, row := range rows {
  2922. if len(fn.Args) > 0 {
  2923. val, _ := e.evalExpr(fn.Args[0], row)
  2924. if val != nil && (min == nil || compare(val, min) < 0) {
  2925. min = val
  2926. }
  2927. }
  2928. }
  2929. return min, nil
  2930. case "MAX":
  2931. var max interface{}
  2932. for _, row := range rows {
  2933. if len(fn.Args) > 0 {
  2934. val, _ := e.evalExpr(fn.Args[0], row)
  2935. if val != nil && (max == nil || compare(val, max) > 0) {
  2936. max = val
  2937. }
  2938. }
  2939. }
  2940. return max, nil
  2941. default:
  2942. // Try scalar function
  2943. if len(rows) > 0 {
  2944. return e.evalFunctionCall(fn, rows[0])
  2945. }
  2946. return nil, nil
  2947. }
  2948. }
  2949. // evalExprWithAggregates evaluates an expression that may contain aggregate functions
  2950. func (e *Executor) evalExprWithAggregates(expr parser.Expr, rows []storage.Row) (interface{}, error) {
  2951. switch ex := expr.(type) {
  2952. case *parser.BinaryExpr:
  2953. left, err := e.evalExprWithAggregates(ex.Left, rows)
  2954. if err != nil {
  2955. return nil, err
  2956. }
  2957. right, err := e.evalExprWithAggregates(ex.Right, rows)
  2958. if err != nil {
  2959. return nil, err
  2960. }
  2961. // Apply the binary operator
  2962. switch ex.Op {
  2963. case lexer.TokenPlus:
  2964. return toFloat(left) + toFloat(right), nil
  2965. case lexer.TokenMinus:
  2966. return toFloat(left) - toFloat(right), nil
  2967. case lexer.TokenStar:
  2968. return toFloat(left) * toFloat(right), nil
  2969. case lexer.TokenSlash:
  2970. r := toFloat(right)
  2971. if r == 0 {
  2972. return nil, nil
  2973. }
  2974. return toFloat(left) / r, nil
  2975. case lexer.TokenPercent:
  2976. return int64(toFloat(left)) % int64(toFloat(right)), nil
  2977. case lexer.TokenEq:
  2978. return compare(left, right) == 0, nil
  2979. case lexer.TokenNeq:
  2980. return compare(left, right) != 0, nil
  2981. case lexer.TokenLt:
  2982. return compare(left, right) < 0, nil
  2983. case lexer.TokenLte:
  2984. return compare(left, right) <= 0, nil
  2985. case lexer.TokenGt:
  2986. return compare(left, right) > 0, nil
  2987. case lexer.TokenGte:
  2988. return compare(left, right) >= 0, nil
  2989. case lexer.TokenAND:
  2990. return toBool(left) && toBool(right), nil
  2991. case lexer.TokenOR:
  2992. return toBool(left) || toBool(right), nil
  2993. case lexer.TokenConcat:
  2994. return toString(left) + toString(right), nil
  2995. default:
  2996. return nil, fmt.Errorf("unsupported operator: %v", ex.Op)
  2997. }
  2998. case *parser.FunctionCall:
  2999. return e.evalAggregateExpr(expr, rows)
  3000. default:
  3001. // Non-aggregate expression, use first row
  3002. if len(rows) > 0 {
  3003. return e.evalExpr(expr, rows[0])
  3004. }
  3005. return nil, nil
  3006. }
  3007. }
  3008. // Helper functions
  3009. func (e *Executor) getSelectColumns(stmt *parser.SelectStmt, schema *storage.Schema) []string {
  3010. var columns []string
  3011. for _, col := range stmt.Columns {
  3012. if col.Star {
  3013. for _, c := range schema.Columns {
  3014. columns = append(columns, c.Name)
  3015. }
  3016. } else if col.Alias != "" {
  3017. columns = append(columns, col.Alias)
  3018. } else if ref, ok := col.Expr.(*parser.ColumnRef); ok {
  3019. columns = append(columns, ref.Column)
  3020. } else {
  3021. columns = append(columns, fmt.Sprintf("column%d", len(columns)+1))
  3022. }
  3023. }
  3024. return columns
  3025. }
  3026. func (e *Executor) hasAggregates(columns []parser.SelectColumn) bool {
  3027. for _, col := range columns {
  3028. if e.isAggregate(col.Expr) {
  3029. return true
  3030. }
  3031. }
  3032. return false
  3033. }
  3034. func (e *Executor) isAggregate(expr parser.Expr) bool {
  3035. if fn, ok := expr.(*parser.FunctionCall); ok {
  3036. name := strings.ToUpper(fn.Name)
  3037. switch name {
  3038. case "COUNT", "SUM", "AVG", "MIN", "MAX", "TOTAL", "GROUP_CONCAT":
  3039. return true
  3040. }
  3041. return false
  3042. }
  3043. switch ex := expr.(type) {
  3044. case *parser.UnaryExpr:
  3045. return e.isAggregate(ex.Operand)
  3046. case *parser.BinaryExpr:
  3047. return e.isAggregate(ex.Left) || e.isAggregate(ex.Right)
  3048. case *parser.ParenExpr:
  3049. return e.isAggregate(ex.Expr)
  3050. case *parser.CaseExpr:
  3051. for _, w := range ex.Whens {
  3052. if e.isAggregate(w.Result) {
  3053. return true
  3054. }
  3055. }
  3056. if ex.Else != nil {
  3057. return e.isAggregate(ex.Else)
  3058. }
  3059. }
  3060. return false
  3061. }
  3062. func (e *Executor) buildGroupKey(groupBy []parser.Expr, row storage.Row) string {
  3063. var parts []string
  3064. for _, expr := range groupBy {
  3065. val, _ := e.evalExpr(expr, row)
  3066. parts = append(parts, fmt.Sprintf("%v", val))
  3067. }
  3068. return strings.Join(parts, "|")
  3069. }
  3070. // resolveOrderByPositions replaces positional ORDER BY expressions (e.g. ORDER BY 1)
  3071. // with the corresponding SELECT column expressions per SQL-92 semantics.
  3072. func resolveOrderByPositions(orderBy []parser.OrderByItem, selectCols []parser.SelectColumn) []parser.OrderByItem {
  3073. result := make([]parser.OrderByItem, len(orderBy))
  3074. for i, item := range orderBy {
  3075. if lit, ok := item.Expr.(*parser.LiteralExpr); ok {
  3076. if pos, err := strconv.Atoi(lit.Value); err == nil && pos >= 1 && pos <= len(selectCols) {
  3077. col := selectCols[pos-1]
  3078. if col.Expr != nil {
  3079. result[i] = parser.OrderByItem{Expr: col.Expr, Desc: item.Desc}
  3080. continue
  3081. }
  3082. }
  3083. }
  3084. result[i] = item
  3085. }
  3086. return result
  3087. }
  3088. func (e *Executor) sortRows(rows []storage.Row, orderBy []parser.OrderByItem) {
  3089. sort.Slice(rows, func(i, j int) bool {
  3090. for _, item := range orderBy {
  3091. vi, _ := e.evalExpr(item.Expr, rows[i])
  3092. vj, _ := e.evalExpr(item.Expr, rows[j])
  3093. cmp := compare(vi, vj)
  3094. if cmp != 0 {
  3095. if item.Desc {
  3096. return cmp > 0
  3097. }
  3098. return cmp < 0
  3099. }
  3100. }
  3101. return false
  3102. })
  3103. }
  3104. // sortResultRows sorts Result.Rows based on ORDER BY clauses.
  3105. // It handles column aliases by matching them against the select columns.
  3106. func (e *Executor) sortResultRows(result *Result, orderBy []parser.OrderByItem, selectColumns []parser.SelectColumn, columnNames []string) {
  3107. orderBy = resolveOrderByPositions(orderBy, selectColumns)
  3108. sort.Slice(result.Rows, func(i, j int) bool {
  3109. for _, item := range orderBy {
  3110. var vi, vj interface{}
  3111. var rowI, rowJ storage.Row
  3112. // Check if ORDER BY references a column alias
  3113. if ref, ok := item.Expr.(*parser.ColumnRef); ok && ref.Table == "" {
  3114. // Look for matching alias in select columns
  3115. for idx, name := range columnNames {
  3116. if strings.EqualFold(name, ref.Column) {
  3117. if idx < len(result.Rows[i]) {
  3118. vi = result.Rows[i][idx]
  3119. vj = result.Rows[j][idx]
  3120. goto compare
  3121. }
  3122. }
  3123. }
  3124. }
  3125. // If not found as alias, try to evaluate the expression
  3126. // Create temporary rows from result rows for evaluation
  3127. rowI = e.resultRowToStorageRow(result, i)
  3128. rowJ = e.resultRowToStorageRow(result, j)
  3129. vi, _ = e.evalExpr(item.Expr, rowI)
  3130. vj, _ = e.evalExpr(item.Expr, rowJ)
  3131. compare:
  3132. cmp := compare(vi, vj)
  3133. if cmp != 0 {
  3134. if item.Desc {
  3135. return cmp > 0
  3136. }
  3137. return cmp < 0
  3138. }
  3139. }
  3140. return false
  3141. })
  3142. }
  3143. // resultRowToStorageRow converts a Result row back to storage.Row for expression evaluation.
  3144. func (e *Executor) resultRowToStorageRow(result *Result, rowIdx int) storage.Row {
  3145. row := make(storage.Row)
  3146. for colIdx, colName := range result.Columns {
  3147. if colIdx < len(result.Rows[rowIdx]) {
  3148. row[colName] = result.Rows[rowIdx][colIdx]
  3149. }
  3150. }
  3151. return row
  3152. }
  3153. func (e *Executor) evalIntExpr(expr parser.Expr) int {
  3154. val, _ := e.evalExpr(expr, nil)
  3155. return int(toFloat(val))
  3156. }
  3157. // Type conversion helpers
  3158. func toFloat(v interface{}) float64 {
  3159. switch val := v.(type) {
  3160. case nil:
  3161. return 0
  3162. case int64:
  3163. return float64(val)
  3164. case int:
  3165. return float64(val)
  3166. case float64:
  3167. return val
  3168. case bool:
  3169. if val {
  3170. return 1
  3171. }
  3172. return 0
  3173. case string:
  3174. f, _ := strconv.ParseFloat(val, 64)
  3175. return f
  3176. default:
  3177. return 0
  3178. }
  3179. }
  3180. func toBool(v interface{}) bool {
  3181. switch val := v.(type) {
  3182. case nil:
  3183. return false
  3184. case bool:
  3185. return val
  3186. case int64:
  3187. return val != 0
  3188. case int:
  3189. return val != 0
  3190. case float64:
  3191. return val != 0
  3192. case string:
  3193. return val != "" && val != "0" && strings.ToLower(val) != "false"
  3194. default:
  3195. return false
  3196. }
  3197. }
  3198. func toString(v interface{}) string {
  3199. if v == nil {
  3200. return ""
  3201. }
  3202. return fmt.Sprintf("%v", v)
  3203. }
  3204. func compare(a, b interface{}) int {
  3205. if a == nil && b == nil {
  3206. return 0
  3207. }
  3208. if a == nil {
  3209. return -1
  3210. }
  3211. if b == nil {
  3212. return 1
  3213. }
  3214. // Try numeric comparison
  3215. fa, oka := toNumeric(a)
  3216. fb, okb := toNumeric(b)
  3217. if oka && okb {
  3218. if fa < fb {
  3219. return -1
  3220. }
  3221. if fa > fb {
  3222. return 1
  3223. }
  3224. return 0
  3225. }
  3226. // String comparison
  3227. sa := toString(a)
  3228. sb := toString(b)
  3229. return strings.Compare(sa, sb)
  3230. }
  3231. func toNumeric(v interface{}) (float64, bool) {
  3232. switch val := v.(type) {
  3233. case int64:
  3234. return float64(val), true
  3235. case int:
  3236. return float64(val), true
  3237. case float64:
  3238. return val, true
  3239. case string:
  3240. f, err := strconv.ParseFloat(val, 64)
  3241. return f, err == nil
  3242. default:
  3243. return 0, false
  3244. }
  3245. }
  3246. // splitANDClauses flattens a tree of AND binary expressions into a slice of leaf conditions.
  3247. func splitANDClauses(expr parser.Expr) []parser.Expr {
  3248. if bin, ok := expr.(*parser.BinaryExpr); ok && bin.Op == lexer.TokenAND {
  3249. left := splitANDClauses(bin.Left)
  3250. right := splitANDClauses(bin.Right)
  3251. return append(left, right...)
  3252. }
  3253. return []parser.Expr{expr}
  3254. }
  3255. // collectColumnRefs returns all unqualified column names referenced in an expression.
  3256. func collectColumnRefs(expr parser.Expr) []string {
  3257. var refs []string
  3258. var walk func(parser.Expr)
  3259. walk = func(e parser.Expr) {
  3260. if e == nil {
  3261. return
  3262. }
  3263. switch n := e.(type) {
  3264. case *parser.ColumnRef:
  3265. refs = append(refs, n.Column)
  3266. case *parser.BinaryExpr:
  3267. walk(n.Left)
  3268. walk(n.Right)
  3269. case *parser.UnaryExpr:
  3270. walk(n.Operand)
  3271. case *parser.InExpr:
  3272. walk(n.Left)
  3273. for _, v := range n.Values {
  3274. walk(v)
  3275. }
  3276. case *parser.BetweenExpr:
  3277. walk(n.Left)
  3278. walk(n.Low)
  3279. walk(n.High)
  3280. case *parser.LikeExpr:
  3281. walk(n.Left)
  3282. walk(n.Pattern)
  3283. case *parser.IsNullExpr:
  3284. walk(n.Left)
  3285. case *parser.CaseExpr:
  3286. walk(n.Operand)
  3287. for _, w := range n.Whens {
  3288. walk(w.Condition)
  3289. walk(w.Result)
  3290. }
  3291. walk(n.Else)
  3292. case *parser.FunctionCall:
  3293. for _, a := range n.Args {
  3294. walk(a)
  3295. }
  3296. case *parser.ParenExpr:
  3297. walk(n.Expr)
  3298. }
  3299. }
  3300. walk(expr)
  3301. return refs
  3302. }
  3303. // combineAND combines a list of expressions with AND.
  3304. func combineAND(clauses []parser.Expr) parser.Expr {
  3305. if len(clauses) == 0 {
  3306. return nil
  3307. }
  3308. result := clauses[0]
  3309. for _, c := range clauses[1:] {
  3310. result = &parser.BinaryExpr{Left: result, Op: lexer.TokenAND, Right: c}
  3311. }
  3312. return result
  3313. }
  3314. // matchLike matches a string against a SQL LIKE pattern.
  3315. func matchLike(s, pattern string) bool {
  3316. // Simple implementation - convert to lowercase for case-insensitive matching
  3317. s = strings.ToLower(s)
  3318. pattern = strings.ToLower(pattern)
  3319. return matchLikeHelper(s, pattern)
  3320. }
  3321. func matchLikeHelper(s, p string) bool {
  3322. if p == "" {
  3323. return s == ""
  3324. }
  3325. if p[0] == '%' {
  3326. // % matches any sequence
  3327. for i := 0; i <= len(s); i++ {
  3328. if matchLikeHelper(s[i:], p[1:]) {
  3329. return true
  3330. }
  3331. }
  3332. return false
  3333. }
  3334. if s == "" {
  3335. return false
  3336. }
  3337. if p[0] == '_' || p[0] == s[0] {
  3338. return matchLikeHelper(s[1:], p[1:])
  3339. }
  3340. return false
  3341. }
  3342. // matchGlob matches a string against a GLOB pattern.
  3343. // GLOB uses * for any sequence and ? for single character (case-sensitive).
  3344. func matchGlob(pattern, s string) bool {
  3345. return matchGlobHelper(pattern, s)
  3346. }
  3347. func matchGlobHelper(p, s string) bool {
  3348. if p == "" {
  3349. return s == ""
  3350. }
  3351. if p[0] == '*' {
  3352. // * matches any sequence
  3353. for i := 0; i <= len(s); i++ {
  3354. if matchGlobHelper(p[1:], s[i:]) {
  3355. return true
  3356. }
  3357. }
  3358. return false
  3359. }
  3360. if s == "" {
  3361. return false
  3362. }
  3363. if p[0] == '?' || p[0] == s[0] {
  3364. return matchGlobHelper(p[1:], s[1:])
  3365. }
  3366. // Handle character classes [...]
  3367. if p[0] == '[' {
  3368. end := strings.Index(p, "]")
  3369. if end > 0 {
  3370. class := p[1:end]
  3371. match := false
  3372. negate := false
  3373. if len(class) > 0 && class[0] == '^' {
  3374. negate = true
  3375. class = class[1:]
  3376. }
  3377. for _, c := range class {
  3378. if byte(c) == s[0] {
  3379. match = true
  3380. break
  3381. }
  3382. }
  3383. if negate {
  3384. match = !match
  3385. }
  3386. if match {
  3387. return matchGlobHelper(p[end+1:], s[1:])
  3388. }
  3389. }
  3390. }
  3391. return false
  3392. }
  3393. // applyDistinct removes duplicate rows from the result
  3394. func (e *Executor) applyDistinct(rows [][]interface{}) [][]interface{} {
  3395. if len(rows) == 0 {
  3396. return rows
  3397. }
  3398. seen := make(map[string]bool)
  3399. uniqueRows := make([][]interface{}, 0)
  3400. for _, row := range rows {
  3401. // Create a key from all column values
  3402. key := ""
  3403. for i, val := range row {
  3404. if i > 0 {
  3405. key += "\x00" // Use null byte as separator
  3406. }
  3407. key += fmt.Sprintf("%v", val)
  3408. }
  3409. if !seen[key] {
  3410. seen[key] = true
  3411. uniqueRows = append(uniqueRows, row)
  3412. }
  3413. }
  3414. return uniqueRows
  3415. }