2
0

executor_test.go 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771
  1. package executor
  2. import (
  3. "fmt"
  4. "testing"
  5. "time"
  6. "github.com/danfragoso/pizzasql-next/pkg/lexer"
  7. "github.com/danfragoso/pizzasql-next/pkg/parser"
  8. "github.com/danfragoso/pizzasql-next/pkg/storage"
  9. )
  10. func parse(t *testing.T, sql string) parser.Statement {
  11. t.Helper()
  12. l := lexer.New(sql)
  13. p := parser.New(l)
  14. stmt, err := p.Parse()
  15. if err != nil {
  16. t.Fatalf("parse error: %v", err)
  17. }
  18. return stmt
  19. }
  20. // execSQL parses and executes a SQL string, used by benchmarks
  21. func execSQL(exec *Executor, sql string) (*Result, error) {
  22. l := lexer.New(sql)
  23. p := parser.New(l)
  24. stmt, err := p.Parse()
  25. if err != nil {
  26. return nil, fmt.Errorf("parse error: %w", err)
  27. }
  28. return exec.Execute(stmt)
  29. }
  30. // Test expression evaluation without database
  31. func TestEvalLiteral(t *testing.T) {
  32. exec := &Executor{}
  33. tests := []struct {
  34. input string
  35. expected interface{}
  36. }{
  37. {"42", int64(42)},
  38. {"3.14", 3.14},
  39. {"'hello'", "hello"},
  40. {"TRUE", true},
  41. {"FALSE", false},
  42. }
  43. for _, tt := range tests {
  44. t.Run(tt.input, func(t *testing.T) {
  45. stmt := parse(t, "SELECT "+tt.input)
  46. sel := stmt.(*parser.SelectStmt)
  47. val, err := exec.evalExpr(sel.Columns[0].Expr, nil)
  48. if err != nil {
  49. t.Errorf("evalExpr error: %v", err)
  50. return
  51. }
  52. if val != tt.expected {
  53. t.Errorf("expected %v (%T), got %v (%T)", tt.expected, tt.expected, val, val)
  54. }
  55. })
  56. }
  57. }
  58. func TestEvalArithmetic(t *testing.T) {
  59. exec := &Executor{}
  60. tests := []struct {
  61. input string
  62. expected float64
  63. }{
  64. {"1 + 2", 3},
  65. {"5 - 3", 2},
  66. {"4 * 3", 12},
  67. {"10 / 2", 5},
  68. {"1 + 2 * 3", 7},
  69. {"(1 + 2) * 3", 9},
  70. {"-5", -5},
  71. {"10 % 3", 1},
  72. }
  73. for _, tt := range tests {
  74. t.Run(tt.input, func(t *testing.T) {
  75. stmt := parse(t, "SELECT "+tt.input)
  76. sel := stmt.(*parser.SelectStmt)
  77. val, err := exec.evalExpr(sel.Columns[0].Expr, nil)
  78. if err != nil {
  79. t.Errorf("evalExpr error: %v", err)
  80. return
  81. }
  82. if toFloat(val) != tt.expected {
  83. t.Errorf("expected %v, got %v", tt.expected, val)
  84. }
  85. })
  86. }
  87. }
  88. func TestEvalConstantWhereClause(t *testing.T) {
  89. // Test constant WHERE clauses that don't reference any columns
  90. tests := []struct {
  91. name string
  92. expr string
  93. expected bool
  94. }{
  95. {"NULL IS NULL", "NULL IS NULL", true},
  96. {"NULL IS NOT NULL", "NULL IS NOT NULL", false},
  97. {"NOT NULL IS NOT NULL", "NOT NULL IS NOT NULL", true},
  98. {"79 IS NOT NULL", "79 IS NOT NULL", true},
  99. {"79 IS NULL", "79 IS NULL", false},
  100. {"+ 79 IS NOT NULL", "+ 79 IS NOT NULL", true},
  101. {"- 78 IS NOT NULL", "- 78 IS NOT NULL", true},
  102. }
  103. exec := &Executor{}
  104. for _, tt := range tests {
  105. t.Run(tt.name, func(t *testing.T) {
  106. stmt := parse(t, "SELECT 1 WHERE "+tt.expr)
  107. sel := stmt.(*parser.SelectStmt)
  108. val, err := exec.evalExpr(sel.Where, nil)
  109. if err != nil {
  110. t.Fatalf("evalExpr error: %v", err)
  111. }
  112. result := toBool(val)
  113. if result != tt.expected {
  114. t.Errorf("expected %v, got %v", tt.expected, result)
  115. }
  116. })
  117. }
  118. }
  119. func TestConstantWhereClauseWithTable(t *testing.T) {
  120. // This test requires a real database connection
  121. // Skip if not available
  122. tests := []struct {
  123. name string
  124. whereClause string
  125. expectAllRows bool
  126. expectNoRows bool
  127. }{
  128. {"WHERE NULL IS NULL", "NULL IS NULL", true, false},
  129. {"WHERE NULL IS NOT NULL", "NULL IS NOT NULL", false, true},
  130. {"WHERE NOT NULL IS NOT NULL", "NOT NULL IS NOT NULL", true, false},
  131. {"WHERE 79 IS NOT NULL", "79 IS NOT NULL", true, false},
  132. {"WHERE 79 IS NULL", "79 IS NULL", false, true},
  133. {"WHERE + 79 IS NOT NULL", "+ 79 IS NOT NULL", true, false},
  134. {"WHERE - 78 IS NOT NULL", "- 78 IS NOT NULL", true, false},
  135. {"WHERE 1 = 1", "1 = 1", true, false},
  136. {"WHERE 1 = 0", "1 = 0", false, true},
  137. {"WHERE TRUE", "TRUE", true, false},
  138. {"WHERE FALSE", "FALSE", false, true},
  139. }
  140. for _, tt := range tests {
  141. t.Run(tt.name, func(t *testing.T) {
  142. // Parse the WHERE clause
  143. stmt := parse(t, "SELECT col0 FROM test WHERE "+tt.whereClause)
  144. sel := stmt.(*parser.SelectStmt)
  145. // Check that the WHERE clause doesn't reference any columns
  146. refs := collectColumnRefs(sel.Where)
  147. if len(refs) != 0 {
  148. t.Errorf("expected constant WHERE clause (no column refs), got %d refs", len(refs))
  149. }
  150. // Create a minimal executor to test constant evaluation
  151. exec := &Executor{}
  152. val, err := exec.evalExpr(sel.Where, nil)
  153. if err != nil {
  154. t.Fatalf("evalExpr error: %v", err)
  155. }
  156. result := toBool(val)
  157. if tt.expectAllRows && !result {
  158. t.Errorf("expected WHERE to evaluate to TRUE (select all rows), got FALSE")
  159. }
  160. if tt.expectNoRows && result {
  161. t.Errorf("expected WHERE to evaluate to FALSE (select no rows), got TRUE")
  162. }
  163. })
  164. }
  165. }
  166. func TestComparison(t *testing.T) {
  167. exec := &Executor{}
  168. tests := []struct {
  169. input string
  170. expected bool
  171. }{
  172. {"1 = 1", true},
  173. {"1 = 2", false},
  174. {"1 <> 2", true},
  175. {"1 < 2", true},
  176. {"2 > 1", true},
  177. {"1 <= 1", true},
  178. {"1 >= 1", true},
  179. {"'a' = 'a'", true},
  180. {"'a' < 'b'", true},
  181. }
  182. for _, tt := range tests {
  183. t.Run(tt.input, func(t *testing.T) {
  184. stmt := parse(t, "SELECT "+tt.input)
  185. sel := stmt.(*parser.SelectStmt)
  186. val, err := exec.evalExpr(sel.Columns[0].Expr, nil)
  187. if err != nil {
  188. t.Errorf("evalExpr error: %v", err)
  189. return
  190. }
  191. if toBool(val) != tt.expected {
  192. t.Errorf("expected %v, got %v", tt.expected, val)
  193. }
  194. })
  195. }
  196. }
  197. func TestEvalLogical(t *testing.T) {
  198. exec := &Executor{}
  199. tests := []struct {
  200. input string
  201. expected bool
  202. }{
  203. {"TRUE AND TRUE", true},
  204. {"TRUE AND FALSE", false},
  205. {"TRUE OR FALSE", true},
  206. {"FALSE OR FALSE", false},
  207. {"NOT TRUE", false},
  208. {"NOT FALSE", true},
  209. {"1 = 1 AND 2 = 2", true},
  210. {"1 = 1 OR 1 = 2", true},
  211. }
  212. for _, tt := range tests {
  213. t.Run(tt.input, func(t *testing.T) {
  214. stmt := parse(t, "SELECT "+tt.input)
  215. sel := stmt.(*parser.SelectStmt)
  216. val, err := exec.evalExpr(sel.Columns[0].Expr, nil)
  217. if err != nil {
  218. t.Errorf("evalExpr error: %v", err)
  219. return
  220. }
  221. if toBool(val) != tt.expected {
  222. t.Errorf("expected %v, got %v", tt.expected, val)
  223. }
  224. })
  225. }
  226. }
  227. func TestEvalFunctions(t *testing.T) {
  228. exec := &Executor{}
  229. tests := []struct {
  230. input string
  231. expected interface{}
  232. }{
  233. {"UPPER('hello')", "HELLO"},
  234. {"LOWER('HELLO')", "hello"},
  235. {"LENGTH('hello')", int64(5)},
  236. {"ABS(-5)", float64(5)},
  237. {"COALESCE(NULL, 'default')", "default"},
  238. {"COALESCE('value', 'default')", "value"},
  239. {"NULLIF(1, 1)", nil},
  240. {"NULLIF(1, 2)", int64(1)},
  241. {"IFNULL(NULL, 'default')", "default"},
  242. {"IFNULL('value', 'default')", "value"},
  243. {"TYPEOF(42)", "integer"},
  244. {"TYPEOF(3.14)", "real"},
  245. {"TYPEOF('hello')", "text"},
  246. {"TYPEOF(NULL)", "null"},
  247. {"TRIM(' hello ')", "hello"},
  248. {"SUBSTR('hello', 2, 3)", "ell"},
  249. {"REPLACE('hello', 'l', 'L')", "heLLo"},
  250. }
  251. for _, tt := range tests {
  252. t.Run(tt.input, func(t *testing.T) {
  253. stmt := parse(t, "SELECT "+tt.input)
  254. sel := stmt.(*parser.SelectStmt)
  255. val, err := exec.evalExpr(sel.Columns[0].Expr, nil)
  256. if err != nil {
  257. t.Errorf("evalExpr error: %v", err)
  258. return
  259. }
  260. if val != tt.expected {
  261. t.Errorf("expected %v (%T), got %v (%T)", tt.expected, tt.expected, val, val)
  262. }
  263. })
  264. }
  265. }
  266. func TestEvalCase(t *testing.T) {
  267. exec := &Executor{}
  268. tests := []struct {
  269. input string
  270. expected interface{}
  271. }{
  272. {"CASE WHEN TRUE THEN 'yes' ELSE 'no' END", "yes"},
  273. {"CASE WHEN FALSE THEN 'yes' ELSE 'no' END", "no"},
  274. {"CASE WHEN 1 = 1 THEN 'one' WHEN 1 = 2 THEN 'two' ELSE 'other' END", "one"},
  275. {"CASE 1 WHEN 1 THEN 'one' WHEN 2 THEN 'two' ELSE 'other' END", "one"},
  276. {"CASE 2 WHEN 1 THEN 'one' WHEN 2 THEN 'two' ELSE 'other' END", "two"},
  277. }
  278. for _, tt := range tests {
  279. t.Run(tt.input, func(t *testing.T) {
  280. stmt := parse(t, "SELECT "+tt.input)
  281. sel := stmt.(*parser.SelectStmt)
  282. val, err := exec.evalExpr(sel.Columns[0].Expr, nil)
  283. if err != nil {
  284. t.Errorf("evalExpr error: %v", err)
  285. return
  286. }
  287. if val != tt.expected {
  288. t.Errorf("expected %v, got %v", tt.expected, val)
  289. }
  290. })
  291. }
  292. }
  293. func TestEvalIn(t *testing.T) {
  294. exec := &Executor{}
  295. tests := []struct {
  296. input string
  297. expected bool
  298. }{
  299. {"1 IN (1, 2, 3)", true},
  300. {"4 IN (1, 2, 3)", false},
  301. {"1 NOT IN (1, 2, 3)", false},
  302. {"4 NOT IN (1, 2, 3)", true},
  303. {"'a' IN ('a', 'b', 'c')", true},
  304. }
  305. for _, tt := range tests {
  306. t.Run(tt.input, func(t *testing.T) {
  307. stmt := parse(t, "SELECT "+tt.input)
  308. sel := stmt.(*parser.SelectStmt)
  309. val, err := exec.evalExpr(sel.Columns[0].Expr, nil)
  310. if err != nil {
  311. t.Errorf("evalExpr error: %v", err)
  312. return
  313. }
  314. if toBool(val) != tt.expected {
  315. t.Errorf("expected %v, got %v", tt.expected, val)
  316. }
  317. })
  318. }
  319. }
  320. func TestEvalBetween(t *testing.T) {
  321. exec := &Executor{}
  322. tests := []struct {
  323. input string
  324. expected bool
  325. }{
  326. {"5 BETWEEN 1 AND 10", true},
  327. {"0 BETWEEN 1 AND 10", false},
  328. {"11 BETWEEN 1 AND 10", false},
  329. {"5 NOT BETWEEN 1 AND 10", false},
  330. {"0 NOT BETWEEN 1 AND 10", true},
  331. }
  332. for _, tt := range tests {
  333. t.Run(tt.input, func(t *testing.T) {
  334. stmt := parse(t, "SELECT "+tt.input)
  335. sel := stmt.(*parser.SelectStmt)
  336. val, err := exec.evalExpr(sel.Columns[0].Expr, nil)
  337. if err != nil {
  338. t.Errorf("evalExpr error: %v", err)
  339. return
  340. }
  341. if toBool(val) != tt.expected {
  342. t.Errorf("expected %v, got %v", tt.expected, val)
  343. }
  344. })
  345. }
  346. }
  347. func TestEvalLike(t *testing.T) {
  348. exec := &Executor{}
  349. tests := []struct {
  350. input string
  351. expected bool
  352. }{
  353. {"'hello' LIKE 'hello'", true},
  354. {"'hello' LIKE 'h%'", true},
  355. {"'hello' LIKE '%o'", true},
  356. {"'hello' LIKE '%ll%'", true},
  357. {"'hello' LIKE 'h_llo'", true},
  358. {"'hello' LIKE 'world'", false},
  359. {"'hello' NOT LIKE 'world'", true},
  360. }
  361. for _, tt := range tests {
  362. t.Run(tt.input, func(t *testing.T) {
  363. stmt := parse(t, "SELECT "+tt.input)
  364. sel := stmt.(*parser.SelectStmt)
  365. val, err := exec.evalExpr(sel.Columns[0].Expr, nil)
  366. if err != nil {
  367. t.Errorf("evalExpr error: %v", err)
  368. return
  369. }
  370. if toBool(val) != tt.expected {
  371. t.Errorf("expected %v, got %v", tt.expected, val)
  372. }
  373. })
  374. }
  375. }
  376. func TestEvalIsNull(t *testing.T) {
  377. exec := &Executor{}
  378. tests := []struct {
  379. input string
  380. expected bool
  381. }{
  382. {"NULL IS NULL", true},
  383. {"1 IS NULL", false},
  384. {"NULL IS NOT NULL", false},
  385. {"1 IS NOT NULL", true},
  386. }
  387. for _, tt := range tests {
  388. t.Run(tt.input, func(t *testing.T) {
  389. stmt := parse(t, "SELECT "+tt.input)
  390. sel := stmt.(*parser.SelectStmt)
  391. val, err := exec.evalExpr(sel.Columns[0].Expr, nil)
  392. if err != nil {
  393. t.Errorf("evalExpr error: %v", err)
  394. return
  395. }
  396. if toBool(val) != tt.expected {
  397. t.Errorf("expected %v, got %v", tt.expected, val)
  398. }
  399. })
  400. }
  401. }
  402. func TestEvalCast(t *testing.T) {
  403. exec := &Executor{}
  404. tests := []struct {
  405. input string
  406. expected interface{}
  407. }{
  408. {"CAST(3.14 AS INTEGER)", int64(3)},
  409. {"CAST(42 AS REAL)", float64(42)},
  410. {"CAST(123 AS TEXT)", "123"},
  411. }
  412. for _, tt := range tests {
  413. t.Run(tt.input, func(t *testing.T) {
  414. stmt := parse(t, "SELECT "+tt.input)
  415. sel := stmt.(*parser.SelectStmt)
  416. val, err := exec.evalExpr(sel.Columns[0].Expr, nil)
  417. if err != nil {
  418. t.Errorf("evalExpr error: %v", err)
  419. return
  420. }
  421. if val != tt.expected {
  422. t.Errorf("expected %v (%T), got %v (%T)", tt.expected, tt.expected, val, val)
  423. }
  424. })
  425. }
  426. }
  427. func TestEvalWithRow(t *testing.T) {
  428. exec := &Executor{}
  429. row := map[string]interface{}{
  430. "id": int64(1),
  431. "name": "John",
  432. "age": 30,
  433. "active": true,
  434. }
  435. tests := []struct {
  436. input string
  437. expected interface{}
  438. }{
  439. {"id", int64(1)},
  440. {"name", "John"},
  441. {"age", 30},
  442. {"active", true},
  443. {"id + 1", float64(2)},
  444. {"age * 2", float64(60)},
  445. {"name = 'John'", true},
  446. {"age > 25", true},
  447. {"active AND age > 20", true},
  448. }
  449. for _, tt := range tests {
  450. t.Run(tt.input, func(t *testing.T) {
  451. stmt := parse(t, "SELECT "+tt.input)
  452. sel := stmt.(*parser.SelectStmt)
  453. val, err := exec.evalExpr(sel.Columns[0].Expr, row)
  454. if err != nil {
  455. t.Errorf("evalExpr error: %v", err)
  456. return
  457. }
  458. // Handle numeric comparisons
  459. if expected, ok := tt.expected.(float64); ok {
  460. if toFloat(val) != expected {
  461. t.Errorf("expected %v, got %v", tt.expected, val)
  462. }
  463. } else if val != tt.expected {
  464. t.Errorf("expected %v (%T), got %v (%T)", tt.expected, tt.expected, val, val)
  465. }
  466. })
  467. }
  468. }
  469. func TestResultString(t *testing.T) {
  470. result := NewResult("SELECT")
  471. result.AddColumn("id")
  472. result.AddColumn("name")
  473. result.AddRow(int64(1), "Alice")
  474. result.AddRow(int64(2), "Bob")
  475. output := result.String()
  476. // Check that output contains expected elements
  477. if output == "" {
  478. t.Error("expected non-empty output")
  479. }
  480. if result.RowCount != 2 {
  481. t.Errorf("expected 2 rows, got %d", result.RowCount)
  482. }
  483. }
  484. func TestMatchLike(t *testing.T) {
  485. tests := []struct {
  486. s string
  487. pattern string
  488. expected bool
  489. }{
  490. {"hello", "hello", true},
  491. {"hello", "h%", true},
  492. {"hello", "%o", true},
  493. {"hello", "%ll%", true},
  494. {"hello", "h_llo", true},
  495. {"hello", "H%", true}, // case insensitive
  496. {"hello", "world", false},
  497. {"", "%", true},
  498. {"abc", "a%c", true},
  499. {"abc", "a_c", true},
  500. {"abc", "__c", true},
  501. {"abc", "___", true},
  502. {"abc", "____", false},
  503. }
  504. for _, tt := range tests {
  505. t.Run(tt.s+"_"+tt.pattern, func(t *testing.T) {
  506. got := matchLike(tt.s, tt.pattern)
  507. if got != tt.expected {
  508. t.Errorf("matchLike(%q, %q) = %v, want %v", tt.s, tt.pattern, got, tt.expected)
  509. }
  510. })
  511. }
  512. }
  513. // Phase 4: SQLite function tests
  514. func TestEvalSQLiteFunctions(t *testing.T) {
  515. exec := &Executor{}
  516. tests := []struct {
  517. input string
  518. expected interface{}
  519. isInt bool // for RANDOM which returns int64
  520. }{
  521. // PRINTF
  522. {"PRINTF('%d', 42)", "42", false},
  523. {"PRINTF('%s', 'hello')", "hello", false},
  524. {"PRINTF('%d + %d = %d', 1, 2, 3)", "1 + 2 = 3", false},
  525. // HEX
  526. {"HEX('ABC')", "414243", false},
  527. {"HEX('hello')", "68656C6C6F", false},
  528. // INSTR
  529. {"INSTR('hello world', 'world')", int64(7), false},
  530. {"INSTR('hello', 'x')", int64(0), false},
  531. {"INSTR('hello', 'l')", int64(3), false},
  532. // ROUND
  533. {"ROUND(3.14159)", float64(3), false},
  534. {"ROUND(3.14159, 2)", float64(3.14), false},
  535. {"ROUND(3.5)", float64(4), false},
  536. // CONCAT
  537. {"CONCAT('hello', ' ', 'world')", "hello world", false},
  538. {"CONCAT('a', 'b', 'c')", "abc", false},
  539. // MAX/MIN (scalar versions)
  540. {"MAX(1, 5, 3)", int64(5), false},
  541. {"MIN(1, 5, 3)", int64(1), false},
  542. {"MAX('a', 'c', 'b')", "c", false},
  543. }
  544. for _, tt := range tests {
  545. t.Run(tt.input, func(t *testing.T) {
  546. stmt := parse(t, "SELECT "+tt.input)
  547. sel := stmt.(*parser.SelectStmt)
  548. val, err := exec.evalExpr(sel.Columns[0].Expr, nil)
  549. if err != nil {
  550. t.Errorf("evalExpr error: %v", err)
  551. return
  552. }
  553. if val != tt.expected {
  554. t.Errorf("expected %v (%T), got %v (%T)", tt.expected, tt.expected, val, val)
  555. }
  556. })
  557. }
  558. }
  559. func TestEvalRandom(t *testing.T) {
  560. exec := &Executor{}
  561. stmt := parse(t, "SELECT RANDOM()")
  562. sel := stmt.(*parser.SelectStmt)
  563. val, err := exec.evalExpr(sel.Columns[0].Expr, nil)
  564. if err != nil {
  565. t.Fatalf("evalExpr error: %v", err)
  566. }
  567. // RANDOM() should return an int64
  568. if _, ok := val.(int64); !ok {
  569. t.Errorf("RANDOM() should return int64, got %T", val)
  570. }
  571. }
  572. func TestEvalGlob(t *testing.T) {
  573. exec := &Executor{}
  574. tests := []struct {
  575. input string
  576. expected bool
  577. }{
  578. {"GLOB('*.txt', 'file.txt')", true},
  579. {"GLOB('*.txt', 'file.doc')", false},
  580. {"GLOB('hello*', 'hello world')", true},
  581. {"GLOB('h?llo', 'hello')", true},
  582. {"GLOB('h?llo', 'hallo')", true},
  583. {"GLOB('[abc]*', 'apple')", true},
  584. {"GLOB('[abc]*', 'dog')", false},
  585. }
  586. for _, tt := range tests {
  587. t.Run(tt.input, func(t *testing.T) {
  588. stmt := parse(t, "SELECT "+tt.input)
  589. sel := stmt.(*parser.SelectStmt)
  590. val, err := exec.evalExpr(sel.Columns[0].Expr, nil)
  591. if err != nil {
  592. t.Errorf("evalExpr error: %v", err)
  593. return
  594. }
  595. if toBool(val) != tt.expected {
  596. t.Errorf("expected %v, got %v", tt.expected, val)
  597. }
  598. })
  599. }
  600. }
  601. func TestMatchGlob(t *testing.T) {
  602. tests := []struct {
  603. pattern string
  604. s string
  605. expected bool
  606. }{
  607. {"*", "anything", true},
  608. {"*", "", true},
  609. {"?", "a", true},
  610. {"?", "ab", false},
  611. {"a*b", "ab", true},
  612. {"a*b", "aXXXb", true},
  613. {"a*b", "aXXXc", false},
  614. {"[abc]", "a", true},
  615. {"[abc]", "d", false},
  616. {"[^abc]", "d", true},
  617. {"[^abc]", "a", false},
  618. {"*.go", "main.go", true},
  619. {"*.go", "main.txt", false},
  620. }
  621. for _, tt := range tests {
  622. t.Run(tt.pattern+"_"+tt.s, func(t *testing.T) {
  623. got := matchGlob(tt.pattern, tt.s)
  624. if got != tt.expected {
  625. t.Errorf("matchGlob(%q, %q) = %v, want %v", tt.pattern, tt.s, got, tt.expected)
  626. }
  627. })
  628. }
  629. }
  630. // Test subquery expressions
  631. func TestEvalSubqueryExpr(t *testing.T) {
  632. pool, err := storage.NewKVPool("localhost:8085", 5, 5*time.Second)
  633. if err != nil {
  634. t.Skip("PizzaKV not available, skipping subquery tests")
  635. }
  636. defer pool.Close()
  637. schema := storage.NewSchemaManager(pool, "test_subquery_db")
  638. table := storage.NewTableManager(pool, schema, "test_subquery_db")
  639. exec := New(schema, table)
  640. // Setup test tables
  641. execSQL(exec, "DROP TABLE IF EXISTS products")
  642. execSQL(exec, "DROP TABLE IF EXISTS categories")
  643. _, err = execSQL(exec, "CREATE TABLE categories (id INTEGER PRIMARY KEY, name TEXT)")
  644. if err != nil {
  645. t.Fatalf("failed to create categories: %v", err)
  646. }
  647. _, err = execSQL(exec, "CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, category_id INTEGER, price REAL)")
  648. if err != nil {
  649. t.Fatalf("failed to create products: %v", err)
  650. }
  651. // Insert test data
  652. execSQL(exec, "INSERT INTO categories VALUES (1, 'Electronics')")
  653. execSQL(exec, "INSERT INTO categories VALUES (2, 'Books')")
  654. execSQL(exec, "INSERT INTO categories VALUES (3, 'Clothing')")
  655. execSQL(exec, "INSERT INTO products VALUES (1, 'Laptop', 1, 999.99)")
  656. execSQL(exec, "INSERT INTO products VALUES (2, 'Phone', 1, 599.99)")
  657. execSQL(exec, "INSERT INTO products VALUES (3, 'Novel', 2, 19.99)")
  658. execSQL(exec, "INSERT INTO products VALUES (4, 'T-Shirt', 3, 29.99)")
  659. // Test scalar subquery
  660. t.Run("scalar_subquery", func(t *testing.T) {
  661. result, err := execSQL(exec, "SELECT (SELECT MAX(price) FROM products)")
  662. if err != nil {
  663. t.Fatalf("query failed: %v", err)
  664. }
  665. if result.RowCount != 1 {
  666. t.Errorf("expected 1 row, got %d", result.RowCount)
  667. }
  668. if result.Rows[0][0] != 999.99 {
  669. t.Errorf("expected 999.99, got %v", result.Rows[0][0])
  670. }
  671. })
  672. // Test IN subquery
  673. t.Run("in_subquery", func(t *testing.T) {
  674. result, err := execSQL(exec, "SELECT name FROM products WHERE category_id IN (SELECT id FROM categories WHERE name = 'Electronics')")
  675. if err != nil {
  676. t.Fatalf("query failed: %v", err)
  677. }
  678. if result.RowCount != 2 {
  679. t.Errorf("expected 2 rows, got %d", result.RowCount)
  680. }
  681. })
  682. // Test NOT IN subquery
  683. t.Run("not_in_subquery", func(t *testing.T) {
  684. result, err := execSQL(exec, "SELECT name FROM products WHERE category_id NOT IN (SELECT id FROM categories WHERE name = 'Electronics')")
  685. if err != nil {
  686. t.Fatalf("query failed: %v", err)
  687. }
  688. if result.RowCount != 2 {
  689. t.Errorf("expected 2 rows, got %d", result.RowCount)
  690. }
  691. })
  692. // Test EXISTS subquery
  693. t.Run("exists_subquery", func(t *testing.T) {
  694. result, err := execSQL(exec, "SELECT EXISTS (SELECT 1 FROM products WHERE price > 500)")
  695. if err != nil {
  696. t.Fatalf("query failed: %v", err)
  697. }
  698. if result.RowCount != 1 {
  699. t.Errorf("expected 1 row, got %d", result.RowCount)
  700. }
  701. if result.Rows[0][0] != true {
  702. t.Errorf("expected true, got %v", result.Rows[0][0])
  703. }
  704. })
  705. // Test EXISTS with no matches
  706. t.Run("exists_no_match", func(t *testing.T) {
  707. result, err := execSQL(exec, "SELECT EXISTS (SELECT 1 FROM products WHERE price > 10000)")
  708. if err != nil {
  709. t.Fatalf("query failed: %v", err)
  710. }
  711. if result.Rows[0][0] != false {
  712. t.Errorf("expected false, got %v", result.Rows[0][0])
  713. }
  714. })
  715. // Cleanup
  716. execSQL(exec, "DROP TABLE IF EXISTS products")
  717. execSQL(exec, "DROP TABLE IF EXISTS categories")
  718. }
  719. func TestChainedJoinCanHashAgainstEarlierTable(t *testing.T) {
  720. pool, err := storage.NewKVPool("localhost:8085", 5, 5*time.Second)
  721. if err != nil {
  722. t.Skipf("PizzaKV not available: %v", err)
  723. }
  724. defer pool.Close()
  725. schema := storage.NewSchemaManager(pool, "test_chained_join_hash_db")
  726. table := storage.NewTableManager(pool, schema, "test_chained_join_hash_db")
  727. exec := New(schema, table)
  728. for _, sql := range []string{
  729. "DROP TABLE IF EXISTS order_items",
  730. "DROP TABLE IF EXISTS orders",
  731. "DROP TABLE IF EXISTS addresses",
  732. "CREATE TABLE orders (id INTEGER PRIMARY KEY, shipping_address_id INTEGER)",
  733. "CREATE TABLE addresses (id INTEGER PRIMARY KEY, state TEXT)",
  734. "CREATE TABLE order_items (id INTEGER PRIMARY KEY, order_id INTEGER, line_total REAL)",
  735. "INSERT INTO addresses VALUES (1, 'CA')",
  736. "INSERT INTO addresses VALUES (2, 'NY')",
  737. "INSERT INTO orders VALUES (10, 1)",
  738. "INSERT INTO orders VALUES (11, 2)",
  739. "INSERT INTO order_items VALUES (100, 10, 25.0)",
  740. "INSERT INTO order_items VALUES (101, 10, 30.0)",
  741. "INSERT INTO order_items VALUES (102, 11, 10.0)",
  742. } {
  743. if _, err := execSQL(exec, sql); err != nil {
  744. t.Fatalf("%s: %v", sql, err)
  745. }
  746. }
  747. defer execSQL(exec, "DROP TABLE IF EXISTS order_items")
  748. defer execSQL(exec, "DROP TABLE IF EXISTS orders")
  749. defer execSQL(exec, "DROP TABLE IF EXISTS addresses")
  750. result, err := execSQL(exec, `
  751. SELECT a.state, COUNT(oi.id) AS lines, SUM(oi.line_total) AS revenue
  752. FROM orders o
  753. JOIN addresses a ON o.shipping_address_id = a.id
  754. JOIN order_items oi ON oi.order_id = o.id
  755. GROUP BY a.state
  756. ORDER BY a.state
  757. `)
  758. if err != nil {
  759. t.Fatalf("query failed: %v", err)
  760. }
  761. if len(result.Rows) != 2 {
  762. t.Fatalf("expected 2 rows, got %d: %#v", len(result.Rows), result.Rows)
  763. }
  764. if result.Rows[0][0] != "CA" || result.Rows[0][1] != int64(2) {
  765. t.Fatalf("unexpected CA row: %#v", result.Rows[0])
  766. }
  767. if result.Rows[1][0] != "NY" || result.Rows[1][1] != int64(1) {
  768. t.Fatalf("unexpected NY row: %#v", result.Rows[1])
  769. }
  770. }
  771. func TestCorrelatedAggregateSubqueryUsesGroupedResult(t *testing.T) {
  772. pool, err := storage.NewKVPool("localhost:8085", 5, 5*time.Second)
  773. if err != nil {
  774. t.Skipf("PizzaKV not available: %v", err)
  775. }
  776. defer pool.Close()
  777. schema := storage.NewSchemaManager(pool, "test_correlated_agg_cache_db")
  778. table := storage.NewTableManager(pool, schema, "test_correlated_agg_cache_db")
  779. exec := New(schema, table)
  780. for _, sql := range []string{
  781. "DROP TABLE IF EXISTS orders",
  782. "DROP TABLE IF EXISTS users",
  783. "CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT)",
  784. "CREATE TABLE orders (id INTEGER PRIMARY KEY, user_id INTEGER)",
  785. "INSERT INTO users VALUES (1, 'a@example.com')",
  786. "INSERT INTO users VALUES (2, 'b@example.com')",
  787. "INSERT INTO users VALUES (3, 'c@example.com')",
  788. "INSERT INTO orders VALUES (10, 1)",
  789. "INSERT INTO orders VALUES (11, 1)",
  790. "INSERT INTO orders VALUES (12, 3)",
  791. "INSERT INTO orders VALUES (13, 3)",
  792. "INSERT INTO orders VALUES (14, 3)",
  793. } {
  794. if _, err := execSQL(exec, sql); err != nil {
  795. t.Fatalf("%s: %v", sql, err)
  796. }
  797. }
  798. defer execSQL(exec, "DROP TABLE IF EXISTS orders")
  799. defer execSQL(exec, "DROP TABLE IF EXISTS users")
  800. result, err := execSQL(exec, `
  801. SELECT u.id, u.email
  802. FROM users u
  803. WHERE (
  804. SELECT COUNT(*)
  805. FROM orders o
  806. WHERE o.user_id = u.id
  807. ) >= 2
  808. ORDER BY u.id
  809. `)
  810. if err != nil {
  811. t.Fatalf("query failed: %v", err)
  812. }
  813. if len(result.Rows) != 2 {
  814. t.Fatalf("expected 2 rows, got %d: %#v", len(result.Rows), result.Rows)
  815. }
  816. if result.Rows[0][0] != int64(1) || result.Rows[1][0] != int64(3) {
  817. t.Fatalf("unexpected result rows: %#v", result.Rows)
  818. }
  819. }
  820. // Benchmark
  821. func BenchmarkEvalExpr(b *testing.B) {
  822. exec := &Executor{}
  823. stmt := parse(&testing.T{}, "SELECT (1 + 2) * 3 - 4 / 2")
  824. sel := stmt.(*parser.SelectStmt)
  825. expr := sel.Columns[0].Expr
  826. b.ResetTimer()
  827. for i := 0; i < b.N; i++ {
  828. exec.evalExpr(expr, nil)
  829. }
  830. }
  831. // BenchmarkIndexVsNoIndex compares query performance with and without indexes.
  832. // Requires a running PizzaKV instance at localhost:8085.
  833. func BenchmarkIndexVsNoIndex(b *testing.B) {
  834. pool, err := storage.NewKVPool("localhost:8085", 5, 5*time.Second)
  835. if err != nil {
  836. b.Skip("PizzaKV not available, skipping index benchmark")
  837. }
  838. defer pool.Close()
  839. schema := storage.NewSchemaManager(pool, "bench_db")
  840. table := storage.NewTableManager(pool, schema, "bench_db")
  841. exec := New(schema, table)
  842. // Cleanup first to ensure fresh state
  843. execSQL(exec, "DROP INDEX IF EXISTS idx_bench_status")
  844. execSQL(exec, "DROP TABLE IF EXISTS bench_users")
  845. _, err = execSQL(exec, "CREATE TABLE bench_users (id INTEGER PRIMARY KEY, name TEXT, email TEXT, status TEXT)")
  846. if err != nil {
  847. b.Fatalf("failed to create table: %v", err)
  848. }
  849. // Insert 1000 rows
  850. statuses := []string{"active", "inactive", "pending", "suspended"}
  851. for i := 1; i <= 1000; i++ {
  852. status := statuses[i%len(statuses)]
  853. _, err := execSQL(exec, fmt.Sprintf("INSERT INTO bench_users (id, name, email, status) VALUES (%d, 'User%d', 'user%d@test.com', '%s')", i, i, i, status))
  854. if err != nil {
  855. b.Fatalf("failed to insert row %d: %v", i, err)
  856. }
  857. }
  858. // Benchmark WITHOUT index
  859. b.Run("NoIndex", func(b *testing.B) {
  860. for i := 0; i < b.N; i++ {
  861. _, err := execSQL(exec, "SELECT * FROM bench_users WHERE status = 'active'")
  862. if err != nil {
  863. b.Fatalf("query failed: %v", err)
  864. }
  865. }
  866. })
  867. // Create index on status column
  868. _, err = execSQL(exec, "CREATE INDEX idx_bench_status ON bench_users (status)")
  869. if err != nil {
  870. b.Fatalf("failed to create index: %v", err)
  871. }
  872. // Benchmark WITH index
  873. b.Run("WithIndex", func(b *testing.B) {
  874. for i := 0; i < b.N; i++ {
  875. _, err := execSQL(exec, "SELECT * FROM bench_users WHERE status = 'active'")
  876. if err != nil {
  877. b.Fatalf("query failed: %v", err)
  878. }
  879. }
  880. })
  881. // Cleanup
  882. execSQL(exec, "DROP INDEX IF EXISTS idx_bench_status")
  883. execSQL(exec, "DROP TABLE IF EXISTS bench_users")
  884. }
  885. // BenchmarkIndexVsNoIndexLargeTable tests with more rows
  886. func BenchmarkIndexVsNoIndexLargeTable(b *testing.B) {
  887. pool, err := storage.NewKVPool("localhost:8085", 5, 5*time.Second)
  888. if err != nil {
  889. b.Skip("PizzaKV not available, skipping index benchmark")
  890. }
  891. defer pool.Close()
  892. schema := storage.NewSchemaManager(pool, "bench_db")
  893. table := storage.NewTableManager(pool, schema, "bench_db")
  894. exec := New(schema, table)
  895. // Cleanup first to ensure fresh state
  896. execSQL(exec, "DROP INDEX IF EXISTS idx_bench_category")
  897. execSQL(exec, "DROP TABLE IF EXISTS bench_large")
  898. _, err = execSQL(exec, "CREATE TABLE bench_large (id INTEGER PRIMARY KEY, category INTEGER, value TEXT)")
  899. if err != nil {
  900. b.Fatalf("failed to create table: %v", err)
  901. }
  902. // Insert 5000 rows with 100 distinct categories
  903. for i := 1; i <= 5000; i++ {
  904. category := i % 100
  905. _, err := execSQL(exec, fmt.Sprintf("INSERT INTO bench_large (id, category, value) VALUES (%d, %d, 'value_%d')", i, category, i))
  906. if err != nil {
  907. b.Fatalf("failed to insert row %d: %v", i, err)
  908. }
  909. }
  910. // Benchmark WITHOUT index (should scan all 5000 rows)
  911. b.Run("NoIndex_5000rows", func(b *testing.B) {
  912. for i := 0; i < b.N; i++ {
  913. _, err := execSQL(exec, "SELECT * FROM bench_large WHERE category = 42")
  914. if err != nil {
  915. b.Fatalf("query failed: %v", err)
  916. }
  917. }
  918. })
  919. // Create index
  920. _, err = execSQL(exec, "CREATE INDEX idx_bench_category ON bench_large (category)")
  921. if err != nil {
  922. b.Fatalf("failed to create index: %v", err)
  923. }
  924. // Benchmark WITH index (should only retrieve ~50 rows)
  925. b.Run("WithIndex_5000rows", func(b *testing.B) {
  926. for i := 0; i < b.N; i++ {
  927. _, err := execSQL(exec, "SELECT * FROM bench_large WHERE category = 42")
  928. if err != nil {
  929. b.Fatalf("query failed: %v", err)
  930. }
  931. }
  932. })
  933. // Cleanup
  934. execSQL(exec, "DROP INDEX IF EXISTS idx_bench_category")
  935. execSQL(exec, "DROP TABLE IF EXISTS bench_large")
  936. }
  937. // Test transaction statements
  938. func TestTransactions(t *testing.T) {
  939. pool, err := storage.NewKVPool("localhost:8085", 5, 5*time.Second)
  940. if err != nil {
  941. t.Skip("PizzaKV not available, skipping transaction tests")
  942. }
  943. defer pool.Close()
  944. schema := storage.NewSchemaManager(pool, "test_tx_db")
  945. table := storage.NewTableManager(pool, schema, "test_tx_db")
  946. exec := New(schema, table)
  947. // Setup test table
  948. execSQL(exec, "DROP TABLE IF EXISTS tx_test")
  949. _, err = execSQL(exec, "CREATE TABLE tx_test (id INTEGER PRIMARY KEY, value TEXT)")
  950. if err != nil {
  951. t.Fatalf("failed to create table: %v", err)
  952. }
  953. t.Run("begin_transaction", func(t *testing.T) {
  954. result, err := execSQL(exec, "BEGIN")
  955. if err != nil {
  956. t.Fatalf("BEGIN failed: %v", err)
  957. }
  958. if result.CommandTag != "BEGIN" {
  959. t.Errorf("expected StatementType 'BEGIN', got '%s'", result.CommandTag)
  960. }
  961. if !exec.inTransaction {
  962. t.Error("expected inTransaction to be true")
  963. }
  964. // Rollback to reset state
  965. execSQL(exec, "ROLLBACK")
  966. })
  967. t.Run("begin_transaction_keyword", func(t *testing.T) {
  968. result, err := execSQL(exec, "BEGIN TRANSACTION")
  969. if err != nil {
  970. t.Fatalf("BEGIN TRANSACTION failed: %v", err)
  971. }
  972. if result.CommandTag != "BEGIN" {
  973. t.Errorf("expected StatementType 'BEGIN', got '%s'", result.CommandTag)
  974. }
  975. execSQL(exec, "ROLLBACK")
  976. })
  977. t.Run("commit_transaction", func(t *testing.T) {
  978. // Clean up any previous data
  979. execSQL(exec, "DELETE FROM tx_test WHERE id = 1")
  980. execSQL(exec, "BEGIN")
  981. _, err := execSQL(exec, "INSERT INTO tx_test (id, value) VALUES (1, 'test1')")
  982. if err != nil {
  983. t.Fatalf("INSERT failed: %v", err)
  984. }
  985. result, err := execSQL(exec, "COMMIT")
  986. if err != nil {
  987. t.Fatalf("COMMIT failed: %v", err)
  988. }
  989. if result.CommandTag != "COMMIT" {
  990. t.Errorf("expected StatementType 'COMMIT', got '%s'", result.CommandTag)
  991. }
  992. if exec.inTransaction {
  993. t.Error("expected inTransaction to be false after COMMIT")
  994. }
  995. // Verify data was committed
  996. checkResult, _ := execSQL(exec, "SELECT * FROM tx_test WHERE id = 1")
  997. if checkResult.RowCount != 1 {
  998. t.Errorf("expected 1 row after commit, got %d", checkResult.RowCount)
  999. }
  1000. })
  1001. t.Run("rollback_transaction", func(t *testing.T) {
  1002. // Clean up any previous data
  1003. execSQL(exec, "DELETE FROM tx_test WHERE id = 2")
  1004. execSQL(exec, "BEGIN")
  1005. _, err := execSQL(exec, "INSERT INTO tx_test (id, value) VALUES (2, 'test2')")
  1006. if err != nil {
  1007. t.Fatalf("INSERT failed: %v", err)
  1008. }
  1009. result, err := execSQL(exec, "ROLLBACK")
  1010. if err != nil {
  1011. t.Fatalf("ROLLBACK failed: %v", err)
  1012. }
  1013. if result.CommandTag != "ROLLBACK" {
  1014. t.Errorf("expected StatementType 'ROLLBACK', got '%s'", result.CommandTag)
  1015. }
  1016. if exec.inTransaction {
  1017. t.Error("expected inTransaction to be false after ROLLBACK")
  1018. }
  1019. // Verify data was NOT committed (rollback currently doesn't undo changes due to PizzaKV limitations)
  1020. // This is a known limitation - the transaction log is built but rollback doesn't restore state
  1021. checkResult, _ := execSQL(exec, "SELECT * FROM tx_test WHERE id = 2")
  1022. // Note: In the current implementation, rollback doesn't actually undo changes
  1023. // This test documents current behavior
  1024. if checkResult.RowCount == 0 {
  1025. t.Log("ROLLBACK successfully prevented data persistence (ideal)")
  1026. } else {
  1027. t.Log("ROLLBACK did not undo changes (current limitation)")
  1028. }
  1029. })
  1030. t.Run("savepoint_create", func(t *testing.T) {
  1031. execSQL(exec, "BEGIN")
  1032. result, err := execSQL(exec, "SAVEPOINT sp1")
  1033. if err != nil {
  1034. t.Fatalf("SAVEPOINT failed: %v", err)
  1035. }
  1036. if result.CommandTag != "SAVEPOINT" {
  1037. t.Errorf("expected StatementType 'SAVEPOINT', got '%s'", result.CommandTag)
  1038. }
  1039. if len(exec.savepoints) != 1 || exec.savepoints[0] != "sp1" {
  1040. t.Errorf("expected savepoint 'sp1', got %v", exec.savepoints)
  1041. }
  1042. execSQL(exec, "ROLLBACK")
  1043. })
  1044. t.Run("nested_savepoints", func(t *testing.T) {
  1045. execSQL(exec, "BEGIN")
  1046. execSQL(exec, "SAVEPOINT sp1")
  1047. execSQL(exec, "SAVEPOINT sp2")
  1048. execSQL(exec, "SAVEPOINT sp3")
  1049. if len(exec.savepoints) != 3 {
  1050. t.Errorf("expected 3 savepoints, got %d", len(exec.savepoints))
  1051. }
  1052. if exec.savepoints[2] != "sp3" {
  1053. t.Errorf("expected last savepoint to be 'sp3', got '%s'", exec.savepoints[2])
  1054. }
  1055. execSQL(exec, "ROLLBACK")
  1056. })
  1057. t.Run("rollback_to_savepoint", func(t *testing.T) {
  1058. execSQL(exec, "BEGIN")
  1059. execSQL(exec, "INSERT INTO tx_test (id, value) VALUES (10, 'before_sp')")
  1060. execSQL(exec, "SAVEPOINT sp1")
  1061. execSQL(exec, "INSERT INTO tx_test (id, value) VALUES (11, 'after_sp')")
  1062. result, err := execSQL(exec, "ROLLBACK TO sp1")
  1063. if err != nil {
  1064. t.Fatalf("ROLLBACK TO failed: %v", err)
  1065. }
  1066. if result.CommandTag != "ROLLBACK" {
  1067. t.Errorf("expected StatementType 'ROLLBACK', got '%s'", result.CommandTag)
  1068. }
  1069. // Should still be in transaction
  1070. if !exec.inTransaction {
  1071. t.Error("expected to still be in transaction after ROLLBACK TO")
  1072. }
  1073. execSQL(exec, "ROLLBACK")
  1074. })
  1075. t.Run("release_savepoint", func(t *testing.T) {
  1076. execSQL(exec, "BEGIN")
  1077. execSQL(exec, "SAVEPOINT sp1")
  1078. execSQL(exec, "SAVEPOINT sp2")
  1079. result, err := execSQL(exec, "RELEASE sp1")
  1080. if err != nil {
  1081. t.Fatalf("RELEASE failed: %v", err)
  1082. }
  1083. if result.CommandTag != "RELEASE" {
  1084. t.Errorf("expected StatementType 'RELEASE', got '%s'", result.CommandTag)
  1085. }
  1086. // Releasing sp1 should also remove sp2 (all nested savepoints)
  1087. if len(exec.savepoints) != 0 {
  1088. t.Errorf("expected no savepoints after RELEASE, got %d", len(exec.savepoints))
  1089. }
  1090. execSQL(exec, "ROLLBACK")
  1091. })
  1092. t.Run("release_savepoint_explicit", func(t *testing.T) {
  1093. execSQL(exec, "BEGIN")
  1094. execSQL(exec, "SAVEPOINT sp1")
  1095. result, err := execSQL(exec, "RELEASE SAVEPOINT sp1")
  1096. if err != nil {
  1097. t.Fatalf("RELEASE SAVEPOINT failed: %v", err)
  1098. }
  1099. if result.CommandTag != "RELEASE" {
  1100. t.Errorf("expected StatementType 'RELEASE', got '%s'", result.CommandTag)
  1101. }
  1102. execSQL(exec, "ROLLBACK")
  1103. })
  1104. // Cleanup
  1105. execSQL(exec, "DROP TABLE IF EXISTS tx_test")
  1106. }
  1107. // Test subqueries in FROM clause
  1108. func TestSubqueryInFrom(t *testing.T) {
  1109. pool, err := storage.NewKVPool("localhost:8085", 5, 5*time.Second)
  1110. if err != nil {
  1111. t.Skip("PizzaKV not available, skipping subquery in FROM tests")
  1112. }
  1113. defer pool.Close()
  1114. schema := storage.NewSchemaManager(pool, "test_subquery_from_db")
  1115. table := storage.NewTableManager(pool, schema, "test_subquery_from_db")
  1116. exec := New(schema, table)
  1117. // Setup test table
  1118. execSQL(exec, "DROP TABLE IF EXISTS employees")
  1119. _, err = execSQL(exec, "CREATE TABLE employees (id INTEGER PRIMARY KEY, name TEXT, department TEXT, salary INTEGER)")
  1120. if err != nil {
  1121. t.Fatalf("failed to create table: %v", err)
  1122. }
  1123. // Insert test data
  1124. execSQL(exec, "INSERT INTO employees (id, name, department, salary) VALUES (1, 'Alice', 'Engineering', 100000)")
  1125. execSQL(exec, "INSERT INTO employees (id, name, department, salary) VALUES (2, 'Bob', 'Engineering', 90000)")
  1126. execSQL(exec, "INSERT INTO employees (id, name, department, salary) VALUES (3, 'Charlie', 'Sales', 80000)")
  1127. execSQL(exec, "INSERT INTO employees (id, name, department, salary) VALUES (4, 'Diana', 'Sales', 75000)")
  1128. t.Run("simple_subquery_from", func(t *testing.T) {
  1129. result, err := execSQL(exec, "SELECT * FROM (SELECT name, department FROM employees) AS emp")
  1130. if err != nil {
  1131. t.Fatalf("query failed: %v", err)
  1132. }
  1133. if result.RowCount != 4 {
  1134. t.Errorf("expected 4 rows, got %d", result.RowCount)
  1135. }
  1136. if len(result.Columns) != 2 {
  1137. t.Errorf("expected 2 columns, got %d", len(result.Columns))
  1138. }
  1139. })
  1140. t.Run("subquery_with_where", func(t *testing.T) {
  1141. result, err := execSQL(exec, "SELECT name FROM (SELECT id, name, salary FROM employees WHERE salary > 80000) AS high_earners")
  1142. if err != nil {
  1143. t.Fatalf("query failed: %v", err)
  1144. }
  1145. if result.RowCount != 2 {
  1146. t.Errorf("expected 2 rows, got %d", result.RowCount)
  1147. }
  1148. })
  1149. t.Run("subquery_with_outer_where", func(t *testing.T) {
  1150. result, err := execSQL(exec, "SELECT * FROM (SELECT name, department FROM employees) AS emp WHERE department = 'Engineering'")
  1151. if err != nil {
  1152. t.Fatalf("query failed: %v", err)
  1153. }
  1154. if result.RowCount != 2 {
  1155. t.Errorf("expected 2 rows, got %d", result.RowCount)
  1156. }
  1157. })
  1158. t.Run("subquery_select_specific_columns", func(t *testing.T) {
  1159. result, err := execSQL(exec, "SELECT name FROM (SELECT id, name, department FROM employees WHERE department = 'Sales') AS sales_emp")
  1160. if err != nil {
  1161. t.Fatalf("query failed: %v", err)
  1162. }
  1163. if result.RowCount != 2 {
  1164. t.Errorf("expected 2 rows, got %d", result.RowCount)
  1165. }
  1166. if len(result.Columns) != 1 || result.Columns[0] != "name" {
  1167. t.Errorf("expected column 'name', got %v", result.Columns)
  1168. }
  1169. })
  1170. t.Run("nested_subquery", func(t *testing.T) {
  1171. result, err := execSQL(exec, "SELECT * FROM (SELECT * FROM (SELECT name FROM employees) AS inner_q) AS outer_q")
  1172. if err != nil {
  1173. t.Fatalf("query failed: %v", err)
  1174. }
  1175. if result.RowCount != 4 {
  1176. t.Errorf("expected 4 rows, got %d", result.RowCount)
  1177. }
  1178. })
  1179. // Cleanup
  1180. execSQL(exec, "DROP TABLE IF EXISTS employees")
  1181. }
  1182. // Test ALTER TABLE statements
  1183. func TestAlterTable(t *testing.T) {
  1184. pool, err := storage.NewKVPool("localhost:8085", 5, 5*time.Second)
  1185. if err != nil {
  1186. t.Skip("PizzaKV not available, skipping ALTER TABLE tests")
  1187. }
  1188. defer pool.Close()
  1189. schema := storage.NewSchemaManager(pool, "test_alter_db")
  1190. table := storage.NewTableManager(pool, schema, "test_alter_db")
  1191. exec := New(schema, table)
  1192. // Setup test table
  1193. execSQL(exec, "DROP TABLE IF EXISTS test_alter")
  1194. _, err = execSQL(exec, "CREATE TABLE test_alter (id INTEGER PRIMARY KEY, name TEXT)")
  1195. if err != nil {
  1196. t.Fatalf("failed to create table: %v", err)
  1197. }
  1198. t.Run("add_column", func(t *testing.T) {
  1199. _, err := execSQL(exec, "ALTER TABLE test_alter ADD COLUMN age INTEGER")
  1200. if err != nil {
  1201. t.Fatalf("ALTER TABLE ADD COLUMN failed: %v", err)
  1202. }
  1203. // Verify column was added
  1204. tSchema, err := schema.GetSchema("test_alter")
  1205. if err != nil {
  1206. t.Fatalf("failed to get schema: %v", err)
  1207. }
  1208. found := false
  1209. for _, col := range tSchema.Columns {
  1210. if col.Name == "age" {
  1211. found = true
  1212. if col.Type != "INTEGER" {
  1213. t.Errorf("expected type INTEGER, got %s", col.Type)
  1214. }
  1215. break
  1216. }
  1217. }
  1218. if !found {
  1219. t.Error("column 'age' not found after ADD COLUMN")
  1220. }
  1221. })
  1222. t.Run("add_column_optional_keyword", func(t *testing.T) {
  1223. _, err := execSQL(exec, "ALTER TABLE test_alter ADD email TEXT")
  1224. if err != nil {
  1225. t.Fatalf("ALTER TABLE ADD failed: %v", err)
  1226. }
  1227. // Verify column was added
  1228. tSchema, _ := schema.GetSchema("test_alter")
  1229. found := false
  1230. for _, col := range tSchema.Columns {
  1231. if col.Name == "email" {
  1232. found = true
  1233. break
  1234. }
  1235. }
  1236. if !found {
  1237. t.Error("column 'email' not found after ADD")
  1238. }
  1239. })
  1240. t.Run("rename_column", func(t *testing.T) {
  1241. _, err := execSQL(exec, "ALTER TABLE test_alter RENAME COLUMN name TO full_name")
  1242. if err != nil {
  1243. t.Fatalf("ALTER TABLE RENAME COLUMN failed: %v", err)
  1244. }
  1245. // Verify column was renamed
  1246. tSchema, _ := schema.GetSchema("test_alter")
  1247. hasOld := false
  1248. hasNew := false
  1249. for _, col := range tSchema.Columns {
  1250. if col.Name == "name" {
  1251. hasOld = true
  1252. }
  1253. if col.Name == "full_name" {
  1254. hasNew = true
  1255. }
  1256. }
  1257. if hasOld {
  1258. t.Error("old column 'name' still exists after RENAME COLUMN")
  1259. }
  1260. if !hasNew {
  1261. t.Error("new column 'full_name' not found after RENAME COLUMN")
  1262. }
  1263. })
  1264. t.Run("drop_column", func(t *testing.T) {
  1265. _, err := execSQL(exec, "ALTER TABLE test_alter DROP COLUMN email")
  1266. if err != nil {
  1267. t.Fatalf("ALTER TABLE DROP COLUMN failed: %v", err)
  1268. }
  1269. // Verify column was dropped
  1270. tSchema, _ := schema.GetSchema("test_alter")
  1271. for _, col := range tSchema.Columns {
  1272. if col.Name == "email" {
  1273. t.Error("column 'email' still exists after DROP COLUMN")
  1274. }
  1275. }
  1276. })
  1277. t.Run("rename_table", func(t *testing.T) {
  1278. _, err := execSQL(exec, "ALTER TABLE test_alter RENAME TO test_renamed")
  1279. if err != nil {
  1280. t.Fatalf("ALTER TABLE RENAME TO failed: %v", err)
  1281. }
  1282. // Verify old table doesn't exist
  1283. _, err = schema.GetSchema("test_alter")
  1284. if err == nil {
  1285. t.Error("old table 'test_alter' still exists after RENAME TO")
  1286. }
  1287. // Verify new table exists
  1288. _, err = schema.GetSchema("test_renamed")
  1289. if err != nil {
  1290. t.Errorf("new table 'test_renamed' not found after RENAME TO: %v", err)
  1291. }
  1292. // Cleanup with new name
  1293. execSQL(exec, "DROP TABLE IF EXISTS test_renamed")
  1294. })
  1295. // Final cleanup
  1296. execSQL(exec, "DROP TABLE IF EXISTS test_alter")
  1297. execSQL(exec, "DROP TABLE IF EXISTS test_renamed")
  1298. }
  1299. func TestExecutorResyncsCatalogAfterExternalCreateTable(t *testing.T) {
  1300. pool, err := storage.NewKVPool("localhost:8085", 5, 5*time.Second)
  1301. if err != nil {
  1302. t.Skip("PizzaKV not available, skipping catalog resync tests")
  1303. }
  1304. defer pool.Close()
  1305. dbName := fmt.Sprintf("test_catalog_create_%d", time.Now().UnixNano())
  1306. schema := storage.NewSchemaManager(pool, dbName)
  1307. table := storage.NewTableManager(pool, schema, dbName)
  1308. staleExec := New(schema, table)
  1309. if err := staleExec.SyncCatalog(); err != nil {
  1310. t.Fatalf("initial sync: %v", err)
  1311. }
  1312. schemaWriter := New(schema, table)
  1313. if _, err := execSQL(schemaWriter, "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)"); err != nil {
  1314. t.Fatalf("create table through second executor: %v", err)
  1315. }
  1316. if _, err := execSQL(schemaWriter, "INSERT INTO users (id, name) VALUES (1, 'Alice')"); err != nil {
  1317. t.Fatalf("insert through second executor: %v", err)
  1318. }
  1319. result, err := execSQL(staleExec, "SELECT name FROM users WHERE id = 1")
  1320. if err != nil {
  1321. t.Fatalf("stale executor should resync and query new table: %v", err)
  1322. }
  1323. if len(result.Rows) != 1 || len(result.Rows[0]) != 1 || result.Rows[0][0] != "Alice" {
  1324. t.Fatalf("unexpected rows after catalog resync: %#v", result.Rows)
  1325. }
  1326. }
  1327. func TestExecutorResyncsCatalogAfterExternalAlterTable(t *testing.T) {
  1328. pool, err := storage.NewKVPool("localhost:8085", 5, 5*time.Second)
  1329. if err != nil {
  1330. t.Skip("PizzaKV not available, skipping catalog resync tests")
  1331. }
  1332. defer pool.Close()
  1333. dbName := fmt.Sprintf("test_catalog_alter_%d", time.Now().UnixNano())
  1334. schema := storage.NewSchemaManager(pool, dbName)
  1335. table := storage.NewTableManager(pool, schema, dbName)
  1336. staleExec := New(schema, table)
  1337. if _, err := execSQL(staleExec, "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)"); err != nil {
  1338. t.Fatalf("create table: %v", err)
  1339. }
  1340. if _, err := execSQL(staleExec, "INSERT INTO users (id, name) VALUES (1, 'Alice')"); err != nil {
  1341. t.Fatalf("insert: %v", err)
  1342. }
  1343. if err := staleExec.SyncCatalog(); err != nil {
  1344. t.Fatalf("sync after create: %v", err)
  1345. }
  1346. schemaWriter := New(schema, table)
  1347. if _, err := execSQL(schemaWriter, "ALTER TABLE users ADD COLUMN status TEXT DEFAULT 'active'"); err != nil {
  1348. t.Fatalf("alter table through second executor: %v", err)
  1349. }
  1350. result, err := execSQL(staleExec, "SELECT status FROM users WHERE id = 1")
  1351. if err != nil {
  1352. t.Fatalf("stale executor should resync and query new column: %v", err)
  1353. }
  1354. if len(result.Rows) != 1 {
  1355. t.Fatalf("expected one row after catalog resync, got %#v", result.Rows)
  1356. }
  1357. }
  1358. // Test ATTACH/DETACH DATABASE statements
  1359. func TestAttachDetach(t *testing.T) {
  1360. pool, err := storage.NewKVPool("localhost:8085", 5, 5*time.Second)
  1361. if err != nil {
  1362. t.Skip("PizzaKV not available, skipping ATTACH/DETACH tests")
  1363. }
  1364. defer pool.Close()
  1365. schema := storage.NewSchemaManager(pool, "test_main_db")
  1366. table := storage.NewTableManager(pool, schema, "test_main_db")
  1367. exec := New(schema, table)
  1368. // Create a table in main database
  1369. execSQL(exec, "DROP TABLE IF EXISTS main_table")
  1370. _, err = execSQL(exec, "CREATE TABLE main_table (id INTEGER PRIMARY KEY, data TEXT)")
  1371. if err != nil {
  1372. t.Fatalf("failed to create main table: %v", err)
  1373. }
  1374. execSQL(exec, "INSERT INTO main_table (id, data) VALUES (1, 'main data')")
  1375. t.Run("attach_database", func(t *testing.T) {
  1376. result, err := execSQL(exec, "ATTACH DATABASE 'test_other_db' AS other")
  1377. if err != nil {
  1378. t.Fatalf("ATTACH DATABASE failed: %v", err)
  1379. }
  1380. if result.CommandTag != "ATTACH" {
  1381. t.Errorf("expected command tag 'ATTACH', got '%s'", result.CommandTag)
  1382. }
  1383. // Verify database is attached
  1384. if _, exists := exec.attachedDatabases["other"]; !exists {
  1385. t.Error("database 'other' not found in attached databases")
  1386. }
  1387. })
  1388. t.Run("attach_duplicate_alias", func(t *testing.T) {
  1389. _, err := execSQL(exec, "ATTACH DATABASE 'test_dup_db' AS other")
  1390. if err == nil {
  1391. t.Error("expected error when attaching with duplicate alias")
  1392. }
  1393. })
  1394. t.Run("attach_reserved_alias", func(t *testing.T) {
  1395. _, err := execSQL(exec, "ATTACH DATABASE 'test_temp_db' AS temp")
  1396. if err == nil {
  1397. t.Error("expected error when using reserved alias 'temp'")
  1398. }
  1399. })
  1400. t.Run("detach_database", func(t *testing.T) {
  1401. result, err := execSQL(exec, "DETACH DATABASE other")
  1402. if err != nil {
  1403. t.Fatalf("DETACH DATABASE failed: %v", err)
  1404. }
  1405. if result.CommandTag != "DETACH" {
  1406. t.Errorf("expected command tag 'DETACH', got '%s'", result.CommandTag)
  1407. }
  1408. // Verify database is detached
  1409. if _, exists := exec.attachedDatabases["other"]; exists {
  1410. t.Error("database 'other' still attached after DETACH")
  1411. }
  1412. })
  1413. t.Run("detach_nonexistent", func(t *testing.T) {
  1414. _, err := execSQL(exec, "DETACH DATABASE nonexistent")
  1415. if err == nil {
  1416. t.Error("expected error when detaching nonexistent database")
  1417. }
  1418. })
  1419. t.Run("detach_main_database", func(t *testing.T) {
  1420. _, err := execSQL(exec, "DETACH DATABASE main")
  1421. if err == nil {
  1422. t.Error("expected error when detaching main database")
  1423. }
  1424. })
  1425. t.Run("attach_without_database_keyword", func(t *testing.T) {
  1426. result, err := execSQL(exec, "ATTACH 'test_short_db' AS short")
  1427. if err != nil {
  1428. t.Fatalf("ATTACH (without DATABASE) failed: %v", err)
  1429. }
  1430. if result.CommandTag != "ATTACH" {
  1431. t.Errorf("expected command tag 'ATTACH', got '%s'", result.CommandTag)
  1432. }
  1433. // Cleanup
  1434. execSQL(exec, "DETACH short")
  1435. })
  1436. t.Run("detach_without_database_keyword", func(t *testing.T) {
  1437. execSQL(exec, "ATTACH 'test_det_db' AS det")
  1438. result, err := execSQL(exec, "DETACH det")
  1439. if err != nil {
  1440. t.Fatalf("DETACH (without DATABASE) failed: %v", err)
  1441. }
  1442. if result.CommandTag != "DETACH" {
  1443. t.Errorf("expected command tag 'DETACH', got '%s'", result.CommandTag)
  1444. }
  1445. })
  1446. // Cleanup
  1447. execSQL(exec, "DROP TABLE IF EXISTS main_table")
  1448. }
  1449. func TestDistinct(t *testing.T) {
  1450. // Simple test without requiring KV connection
  1451. exec := &Executor{}
  1452. // Test applyDistinct function directly
  1453. t.Run("ApplyDistinct", func(t *testing.T) {
  1454. rows := [][]interface{}{
  1455. {"a", 1},
  1456. {"b", 2},
  1457. {"a", 1}, // duplicate
  1458. {"c", 3},
  1459. {"b", 2}, // duplicate
  1460. }
  1461. result := exec.applyDistinct(rows)
  1462. if len(result) != 3 {
  1463. t.Errorf("expected 3 unique rows, got %d", len(result))
  1464. }
  1465. // Check that we have the expected unique rows
  1466. expected := map[string]bool{
  1467. "a\x001": true,
  1468. "b\x002": true,
  1469. "c\x003": true,
  1470. }
  1471. for _, row := range result {
  1472. key := fmt.Sprintf("%v\x00%v", row[0], row[1])
  1473. if !expected[key] {
  1474. t.Errorf("unexpected row in result: %v", row)
  1475. }
  1476. }
  1477. })
  1478. }
  1479. // TestGroupByWithConstantFalseWhere tests the distinction between:
  1480. // 1. Aggregate without GROUP BY + WHERE false -> returns [NULL] (one row with aggregate result on empty set)
  1481. // 2. Aggregate with GROUP BY + WHERE false -> returns [] (no groups match, so no rows)
  1482. func TestGroupByWithConstantFalseWhere(t *testing.T) {
  1483. pool, err := storage.NewKVPool("localhost:8085", 5, 5*time.Second)
  1484. if err != nil {
  1485. t.Skip("PizzaKV not available, skipping test")
  1486. }
  1487. defer pool.Close()
  1488. schema := storage.NewSchemaManager(pool, "test_groupby_db")
  1489. table := storage.NewTableManager(pool, schema, "test_groupby_db")
  1490. exec := New(schema, table)
  1491. // Setup test tables
  1492. execSQL(exec, "DROP TABLE IF EXISTS tab0")
  1493. execSQL(exec, "DROP TABLE IF EXISTS tab1")
  1494. _, err = execSQL(exec, "CREATE TABLE tab0 (col0 INTEGER, col1 INTEGER, col2 INTEGER)")
  1495. if err != nil {
  1496. t.Fatalf("failed to create tab0: %v", err)
  1497. }
  1498. _, err = execSQL(exec, "CREATE TABLE tab1 (col0 INTEGER, col1 INTEGER, col2 INTEGER)")
  1499. if err != nil {
  1500. t.Fatalf("failed to create tab1: %v", err)
  1501. }
  1502. // Insert some test data
  1503. execSQL(exec, "INSERT INTO tab0 VALUES (1, 10, 100)")
  1504. execSQL(exec, "INSERT INTO tab0 VALUES (2, 20, 200)")
  1505. execSQL(exec, "INSERT INTO tab0 VALUES (3, 30, 300)")
  1506. execSQL(exec, "INSERT INTO tab1 VALUES (1, 10, 100)")
  1507. execSQL(exec, "INSERT INTO tab1 VALUES (2, 20, 200)")
  1508. execSQL(exec, "INSERT INTO tab1 VALUES (3, 30, 300)")
  1509. // Test 1: Aggregate with GROUP BY and constant FALSE WHERE -> should return empty result []
  1510. t.Run("aggregate_with_groupby_where_false", func(t *testing.T) {
  1511. result, err := execSQL(exec, "SELECT AVG(col1) FROM tab1 WHERE NULL IS NOT NULL GROUP BY col1")
  1512. if err != nil {
  1513. t.Fatalf("query failed: %v", err)
  1514. }
  1515. if result.RowCount != 0 {
  1516. t.Errorf("expected 0 rows (no groups), got %d rows with values: %v", result.RowCount, result.Rows)
  1517. }
  1518. })
  1519. // Test 2: Aggregate without GROUP BY and constant FALSE WHERE -> should return [NULL]
  1520. t.Run("aggregate_without_groupby_where_false", func(t *testing.T) {
  1521. result, err := execSQL(exec, "SELECT AVG(col1) FROM tab1 WHERE NULL IS NOT NULL")
  1522. if err != nil {
  1523. t.Fatalf("query failed: %v", err)
  1524. }
  1525. if result.RowCount != 1 {
  1526. t.Errorf("expected 1 row, got %d", result.RowCount)
  1527. }
  1528. if result.RowCount == 1 && result.Rows[0][0] != nil {
  1529. t.Errorf("expected NULL for aggregate on empty set, got %v", result.Rows[0][0])
  1530. }
  1531. })
  1532. // Test 3: More complex case from test failures
  1533. t.Run("complex_groupby_where_false", func(t *testing.T) {
  1534. result, err := execSQL(exec, "SELECT ALL AVG(+ col1) FROM tab1 WHERE NULL IS NULL AND NOT NULL IS NULL GROUP BY col1")
  1535. if err != nil {
  1536. t.Fatalf("query failed: %v", err)
  1537. }
  1538. if result.RowCount != 0 {
  1539. t.Errorf("expected 0 rows (no groups), got %d rows with values: %v", result.RowCount, result.Rows)
  1540. }
  1541. })
  1542. // Test 4: DISTINCT aggregate with GROUP BY and constant FALSE WHERE
  1543. t.Run("distinct_aggregate_with_groupby_where_false", func(t *testing.T) {
  1544. result, err := execSQL(exec, "SELECT DISTINCT AVG(DISTINCT - col2) FROM tab0 WHERE NOT NULL IS NULL GROUP BY col2")
  1545. if err != nil {
  1546. t.Fatalf("query failed: %v", err)
  1547. }
  1548. if result.RowCount != 0 {
  1549. t.Errorf("expected 0 rows (no groups), got %d rows with values: %v", result.RowCount, result.Rows)
  1550. }
  1551. })
  1552. // Test 5: Verify normal GROUP BY still works (WHERE true)
  1553. t.Run("normal_groupby_sanity_check", func(t *testing.T) {
  1554. result, err := execSQL(exec, "SELECT AVG(col1) FROM tab1 WHERE NULL IS NULL GROUP BY col1")
  1555. if err != nil {
  1556. t.Fatalf("query failed: %v", err)
  1557. }
  1558. if result.RowCount != 3 {
  1559. t.Errorf("expected 3 groups, got %d", result.RowCount)
  1560. }
  1561. })
  1562. // Cleanup
  1563. execSQL(exec, "DROP TABLE IF EXISTS tab0")
  1564. execSQL(exec, "DROP TABLE IF EXISTS tab1")
  1565. }