offset_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. package engine
  2. import (
  3. "context"
  4. "strconv"
  5. "strings"
  6. "testing"
  7. )
  8. // TestParseSQL_OFFSET_EdgeCases tests edge cases for OFFSET parsing
  9. func TestParseSQL_OFFSET_EdgeCases(t *testing.T) {
  10. tests := []struct {
  11. name string
  12. sql string
  13. wantErr bool
  14. validate func(t *testing.T, stmt Statement, err error)
  15. }{
  16. {
  17. name: "Valid LIMIT OFFSET with WHERE",
  18. sql: "SELECT * FROM users WHERE age > 18 LIMIT 10 OFFSET 5",
  19. wantErr: false,
  20. validate: func(t *testing.T, stmt Statement, err error) {
  21. selectStmt := stmt.(*SelectStatement)
  22. if selectStmt.Limit == nil {
  23. t.Fatal("Expected LIMIT clause, got nil")
  24. }
  25. if selectStmt.Limit.Offset == nil {
  26. t.Fatal("Expected OFFSET clause, got nil")
  27. }
  28. if selectStmt.Where == nil {
  29. t.Fatal("Expected WHERE clause, got nil")
  30. }
  31. },
  32. },
  33. {
  34. name: "LIMIT OFFSET with mixed case",
  35. sql: "select * from users limit 5 offset 3",
  36. wantErr: false,
  37. validate: func(t *testing.T, stmt Statement, err error) {
  38. selectStmt := stmt.(*SelectStatement)
  39. offsetVal := selectStmt.Limit.Offset.(*SQLVal)
  40. if string(offsetVal.Val) != "3" {
  41. t.Errorf("Expected offset value '3', got '%s'", string(offsetVal.Val))
  42. }
  43. },
  44. },
  45. {
  46. name: "LIMIT OFFSET with extra spaces",
  47. sql: "SELECT * FROM users LIMIT 10 OFFSET 20 ",
  48. wantErr: false,
  49. validate: func(t *testing.T, stmt Statement, err error) {
  50. selectStmt := stmt.(*SelectStatement)
  51. limitVal := selectStmt.Limit.Rowcount.(*SQLVal)
  52. offsetVal := selectStmt.Limit.Offset.(*SQLVal)
  53. if string(limitVal.Val) != "10" {
  54. t.Errorf("Expected limit value '10', got '%s'", string(limitVal.Val))
  55. }
  56. if string(offsetVal.Val) != "20" {
  57. t.Errorf("Expected offset value '20', got '%s'", string(offsetVal.Val))
  58. }
  59. },
  60. },
  61. }
  62. for _, tt := range tests {
  63. t.Run(tt.name, func(t *testing.T) {
  64. stmt, err := ParseSQL(tt.sql)
  65. if tt.wantErr {
  66. if err == nil {
  67. t.Errorf("Expected error, but got none")
  68. }
  69. return
  70. }
  71. if err != nil {
  72. t.Errorf("Unexpected error: %v", err)
  73. return
  74. }
  75. if tt.validate != nil {
  76. tt.validate(t, stmt, err)
  77. }
  78. })
  79. }
  80. }
  81. // TestSQLEngine_OFFSET_EdgeCases tests edge cases for OFFSET execution
  82. func TestSQLEngine_OFFSET_EdgeCases(t *testing.T) {
  83. engine := NewTestSQLEngine()
  84. t.Run("OFFSET larger than result set", func(t *testing.T) {
  85. result, err := engine.ExecuteSQL(context.Background(), "SELECT * FROM user_events LIMIT 5 OFFSET 100")
  86. if err != nil {
  87. t.Fatalf("Expected no error, got %v", err)
  88. }
  89. if result.Error != nil {
  90. t.Fatalf("Expected no query error, got %v", result.Error)
  91. }
  92. // Should return empty result set
  93. if len(result.Rows) != 0 {
  94. t.Errorf("Expected 0 rows when OFFSET > total rows, got %d", len(result.Rows))
  95. }
  96. })
  97. t.Run("OFFSET with LIMIT 0", func(t *testing.T) {
  98. result, err := engine.ExecuteSQL(context.Background(), "SELECT * FROM user_events LIMIT 0 OFFSET 2")
  99. if err != nil {
  100. t.Fatalf("Expected no error, got %v", err)
  101. }
  102. if result.Error != nil {
  103. t.Fatalf("Expected no query error, got %v", result.Error)
  104. }
  105. // LIMIT 0 should return no rows regardless of OFFSET
  106. if len(result.Rows) != 0 {
  107. t.Errorf("Expected 0 rows with LIMIT 0, got %d", len(result.Rows))
  108. }
  109. })
  110. t.Run("High OFFSET with small LIMIT", func(t *testing.T) {
  111. result, err := engine.ExecuteSQL(context.Background(), "SELECT * FROM user_events LIMIT 1 OFFSET 3")
  112. if err != nil {
  113. t.Fatalf("Expected no error, got %v", err)
  114. }
  115. if result.Error != nil {
  116. t.Fatalf("Expected no query error, got %v", result.Error)
  117. }
  118. // In clean mock environment, we have 4 live_log rows from unflushed messages
  119. // LIMIT 1 OFFSET 3 should return the 4th row (0-indexed: rows 0,1,2,3 -> return row 3)
  120. if len(result.Rows) != 1 {
  121. t.Errorf("Expected 1 row with LIMIT 1 OFFSET 3 (4th live_log row), got %d", len(result.Rows))
  122. }
  123. })
  124. }
  125. // TestSQLEngine_OFFSET_ErrorCases tests error conditions for OFFSET
  126. func TestSQLEngine_OFFSET_ErrorCases(t *testing.T) {
  127. engine := NewTestSQLEngine()
  128. // Test negative OFFSET - should be caught during execution
  129. t.Run("Negative OFFSET value", func(t *testing.T) {
  130. // Note: This would need to be implemented as validation in the execution engine
  131. // For now, we test that the parser accepts it but execution might handle it
  132. _, err := ParseSQL("SELECT * FROM users LIMIT 10 OFFSET -5")
  133. if err != nil {
  134. t.Logf("Parser rejected negative OFFSET (this is expected): %v", err)
  135. } else {
  136. // Parser accepts it, execution should handle validation
  137. t.Logf("Parser accepts negative OFFSET, execution should validate")
  138. }
  139. })
  140. // Test very large OFFSET
  141. t.Run("Very large OFFSET value", func(t *testing.T) {
  142. largeOffset := "2147483647" // Max int32
  143. sql := "SELECT * FROM user_events LIMIT 1 OFFSET " + largeOffset
  144. result, err := engine.ExecuteSQL(context.Background(), sql)
  145. if err != nil {
  146. // Large OFFSET might cause parsing or execution errors
  147. if strings.Contains(err.Error(), "out of valid range") {
  148. t.Logf("Large OFFSET properly rejected: %v", err)
  149. } else {
  150. t.Errorf("Unexpected error for large OFFSET: %v", err)
  151. }
  152. } else if result.Error != nil {
  153. if strings.Contains(result.Error.Error(), "out of valid range") {
  154. t.Logf("Large OFFSET properly rejected during execution: %v", result.Error)
  155. } else {
  156. t.Errorf("Unexpected execution error for large OFFSET: %v", result.Error)
  157. }
  158. } else {
  159. // Should return empty result for very large offset
  160. if len(result.Rows) != 0 {
  161. t.Errorf("Expected 0 rows for very large OFFSET, got %d", len(result.Rows))
  162. }
  163. }
  164. })
  165. }
  166. // TestSQLEngine_OFFSET_Consistency tests that OFFSET produces consistent results
  167. func TestSQLEngine_OFFSET_Consistency(t *testing.T) {
  168. engine := NewTestSQLEngine()
  169. // Get all rows first
  170. allResult, err := engine.ExecuteSQL(context.Background(), "SELECT * FROM user_events")
  171. if err != nil {
  172. t.Fatalf("Failed to get all rows: %v", err)
  173. }
  174. if allResult.Error != nil {
  175. t.Fatalf("Failed to get all rows: %v", allResult.Error)
  176. }
  177. totalRows := len(allResult.Rows)
  178. if totalRows == 0 {
  179. t.Skip("No data available for consistency test")
  180. }
  181. // Test that OFFSET + remaining rows = total rows
  182. for offset := 0; offset < totalRows; offset++ {
  183. t.Run("OFFSET_"+strconv.Itoa(offset), func(t *testing.T) {
  184. sql := "SELECT * FROM user_events LIMIT 100 OFFSET " + strconv.Itoa(offset)
  185. result, err := engine.ExecuteSQL(context.Background(), sql)
  186. if err != nil {
  187. t.Fatalf("Error with OFFSET %d: %v", offset, err)
  188. }
  189. if result.Error != nil {
  190. t.Fatalf("Query error with OFFSET %d: %v", offset, result.Error)
  191. }
  192. expectedRows := totalRows - offset
  193. if len(result.Rows) != expectedRows {
  194. t.Errorf("OFFSET %d: expected %d rows, got %d", offset, expectedRows, len(result.Rows))
  195. }
  196. })
  197. }
  198. }
  199. // TestSQLEngine_LIMIT_OFFSET_BugFix tests the specific bug fix for LIMIT with OFFSET
  200. // This test addresses the issue where LIMIT 10 OFFSET 5 was returning 5 rows instead of 10
  201. func TestSQLEngine_LIMIT_OFFSET_BugFix(t *testing.T) {
  202. engine := NewTestSQLEngine()
  203. // Test the specific scenario that was broken: LIMIT 10 OFFSET 5 should return 10 rows
  204. t.Run("LIMIT 10 OFFSET 5 returns correct count", func(t *testing.T) {
  205. result, err := engine.ExecuteSQL(context.Background(), "SELECT id, user_id, id+user_id FROM user_events LIMIT 10 OFFSET 5")
  206. if err != nil {
  207. t.Fatalf("Expected no error, got %v", err)
  208. }
  209. if result.Error != nil {
  210. t.Fatalf("Expected no query error, got %v", result.Error)
  211. }
  212. // The bug was that this returned 5 rows instead of 10
  213. // After fix, it should return up to 10 rows (limited by available data)
  214. actualRows := len(result.Rows)
  215. if actualRows > 10 {
  216. t.Errorf("LIMIT 10 violated: got %d rows", actualRows)
  217. }
  218. t.Logf("LIMIT 10 OFFSET 5 returned %d rows (within limit)", actualRows)
  219. // Verify we have the expected columns
  220. expectedCols := 3 // id, user_id, id+user_id
  221. if len(result.Columns) != expectedCols {
  222. t.Errorf("Expected %d columns, got %d columns: %v", expectedCols, len(result.Columns), result.Columns)
  223. }
  224. })
  225. // Test various LIMIT and OFFSET combinations to ensure correct row counts
  226. testCases := []struct {
  227. name string
  228. limit int
  229. offset int
  230. allowEmpty bool // Whether 0 rows is acceptable (for large offsets)
  231. }{
  232. {"LIMIT 5 OFFSET 0", 5, 0, false},
  233. {"LIMIT 5 OFFSET 2", 5, 2, false},
  234. {"LIMIT 8 OFFSET 3", 8, 3, false},
  235. {"LIMIT 15 OFFSET 1", 15, 1, false},
  236. {"LIMIT 3 OFFSET 7", 3, 7, true}, // Large offset may exceed data
  237. {"LIMIT 12 OFFSET 4", 12, 4, true}, // Large offset may exceed data
  238. }
  239. for _, tc := range testCases {
  240. t.Run(tc.name, func(t *testing.T) {
  241. sql := "SELECT id, user_id FROM user_events LIMIT " + strconv.Itoa(tc.limit) + " OFFSET " + strconv.Itoa(tc.offset)
  242. result, err := engine.ExecuteSQL(context.Background(), sql)
  243. if err != nil {
  244. t.Fatalf("Expected no error for %s, got %v", tc.name, err)
  245. }
  246. if result.Error != nil {
  247. t.Fatalf("Expected no query error for %s, got %v", tc.name, result.Error)
  248. }
  249. actualRows := len(result.Rows)
  250. // Verify LIMIT is never exceeded
  251. if actualRows > tc.limit {
  252. t.Errorf("%s: LIMIT violated - returned %d rows, limit was %d", tc.name, actualRows, tc.limit)
  253. }
  254. // Check if we expect rows
  255. if !tc.allowEmpty && actualRows == 0 {
  256. t.Errorf("%s: expected some rows but got 0 (insufficient test data or early termination bug)", tc.name)
  257. }
  258. t.Logf("%s: returned %d rows (within limit %d)", tc.name, actualRows, tc.limit)
  259. })
  260. }
  261. }
  262. // TestSQLEngine_OFFSET_DataCollectionBuffer tests that the enhanced data collection buffer works
  263. func TestSQLEngine_OFFSET_DataCollectionBuffer(t *testing.T) {
  264. engine := NewTestSQLEngine()
  265. // Test scenarios that specifically stress the data collection buffer enhancement
  266. t.Run("Large OFFSET with small LIMIT", func(t *testing.T) {
  267. // This scenario requires collecting more data upfront to handle the offset
  268. result, err := engine.ExecuteSQL(context.Background(), "SELECT * FROM user_events LIMIT 2 OFFSET 8")
  269. if err != nil {
  270. t.Fatalf("Expected no error, got %v", err)
  271. }
  272. if result.Error != nil {
  273. t.Fatalf("Expected no query error, got %v", result.Error)
  274. }
  275. // Should either return 2 rows or 0 (if offset exceeds available data)
  276. // The bug would cause early termination and return 0 incorrectly
  277. actualRows := len(result.Rows)
  278. if actualRows != 0 && actualRows != 2 {
  279. t.Errorf("Expected 0 or 2 rows for LIMIT 2 OFFSET 8, got %d", actualRows)
  280. }
  281. })
  282. t.Run("Medium OFFSET with medium LIMIT", func(t *testing.T) {
  283. result, err := engine.ExecuteSQL(context.Background(), "SELECT id, user_id FROM user_events LIMIT 6 OFFSET 4")
  284. if err != nil {
  285. t.Fatalf("Expected no error, got %v", err)
  286. }
  287. if result.Error != nil {
  288. t.Fatalf("Expected no query error, got %v", result.Error)
  289. }
  290. // With proper buffer enhancement, this should work correctly
  291. actualRows := len(result.Rows)
  292. if actualRows > 6 {
  293. t.Errorf("LIMIT 6 should never return more than 6 rows, got %d", actualRows)
  294. }
  295. })
  296. t.Run("Progressive OFFSET test", func(t *testing.T) {
  297. // Test that increasing OFFSET values work consistently
  298. baseSQL := "SELECT id FROM user_events LIMIT 3 OFFSET "
  299. for offset := 0; offset <= 5; offset++ {
  300. sql := baseSQL + strconv.Itoa(offset)
  301. result, err := engine.ExecuteSQL(context.Background(), sql)
  302. if err != nil {
  303. t.Fatalf("Error at OFFSET %d: %v", offset, err)
  304. }
  305. if result.Error != nil {
  306. t.Fatalf("Query error at OFFSET %d: %v", offset, result.Error)
  307. }
  308. actualRows := len(result.Rows)
  309. // Each should return at most 3 rows (LIMIT 3)
  310. if actualRows > 3 {
  311. t.Errorf("OFFSET %d: LIMIT 3 returned %d rows (should be ≤ 3)", offset, actualRows)
  312. }
  313. t.Logf("OFFSET %d: returned %d rows", offset, actualRows)
  314. }
  315. })
  316. }
  317. // TestSQLEngine_LIMIT_OFFSET_ArithmeticExpressions tests LIMIT/OFFSET with arithmetic expressions
  318. func TestSQLEngine_LIMIT_OFFSET_ArithmeticExpressions(t *testing.T) {
  319. engine := NewTestSQLEngine()
  320. // Test the exact scenario from the user's example
  321. t.Run("Arithmetic expressions with LIMIT OFFSET", func(t *testing.T) {
  322. // First query: LIMIT 10 (should return 10 rows)
  323. result1, err := engine.ExecuteSQL(context.Background(), "SELECT id, user_id, id+user_id FROM user_events LIMIT 10")
  324. if err != nil {
  325. t.Fatalf("Expected no error for first query, got %v", err)
  326. }
  327. if result1.Error != nil {
  328. t.Fatalf("Expected no query error for first query, got %v", result1.Error)
  329. }
  330. // Second query: LIMIT 10 OFFSET 5 (should return 10 rows, not 5)
  331. result2, err := engine.ExecuteSQL(context.Background(), "SELECT id, user_id, id+user_id FROM user_events LIMIT 10 OFFSET 5")
  332. if err != nil {
  333. t.Fatalf("Expected no error for second query, got %v", err)
  334. }
  335. if result2.Error != nil {
  336. t.Fatalf("Expected no query error for second query, got %v", result2.Error)
  337. }
  338. // Verify column structure is correct
  339. expectedColumns := []string{"id", "user_id", "id+user_id"}
  340. if len(result2.Columns) != len(expectedColumns) {
  341. t.Errorf("Expected %d columns, got %d", len(expectedColumns), len(result2.Columns))
  342. }
  343. // The key assertion: LIMIT 10 OFFSET 5 should return 10 rows (if available)
  344. // This was the specific bug reported by the user
  345. rows1 := len(result1.Rows)
  346. rows2 := len(result2.Rows)
  347. t.Logf("LIMIT 10: returned %d rows", rows1)
  348. t.Logf("LIMIT 10 OFFSET 5: returned %d rows", rows2)
  349. if rows1 >= 15 { // If we have enough data for the test to be meaningful
  350. if rows2 != 10 {
  351. t.Errorf("LIMIT 10 OFFSET 5 should return 10 rows when sufficient data available, got %d", rows2)
  352. }
  353. } else {
  354. t.Logf("Insufficient data (%d rows) to fully test LIMIT 10 OFFSET 5 scenario", rows1)
  355. }
  356. // Verify multiplication expressions work in the second query
  357. if len(result2.Rows) > 0 {
  358. for i, row := range result2.Rows {
  359. if len(row) >= 3 { // Check if we have the id+user_id column
  360. idVal := row[0].ToString() // id column
  361. userIdVal := row[1].ToString() // user_id column
  362. sumVal := row[2].ToString() // id+user_id column
  363. t.Logf("Row %d: id=%s, user_id=%s, id+user_id=%s", i, idVal, userIdVal, sumVal)
  364. }
  365. }
  366. }
  367. })
  368. // Test multiplication specifically
  369. t.Run("Multiplication expressions", func(t *testing.T) {
  370. result, err := engine.ExecuteSQL(context.Background(), "SELECT id, id*2 FROM user_events LIMIT 3")
  371. if err != nil {
  372. t.Fatalf("Expected no error for multiplication test, got %v", err)
  373. }
  374. if result.Error != nil {
  375. t.Fatalf("Expected no query error for multiplication test, got %v", result.Error)
  376. }
  377. if len(result.Columns) != 2 {
  378. t.Errorf("Expected 2 columns for multiplication test, got %d", len(result.Columns))
  379. }
  380. if len(result.Rows) == 0 {
  381. t.Error("Expected some rows for multiplication test")
  382. }
  383. // Check that id*2 column has values (not empty)
  384. for i, row := range result.Rows {
  385. if len(row) >= 2 {
  386. idVal := row[0].ToString()
  387. doubledVal := row[1].ToString()
  388. if doubledVal == "" || doubledVal == "0" {
  389. t.Errorf("Row %d: id*2 should not be empty, id=%s, id*2=%s", i, idVal, doubledVal)
  390. } else {
  391. t.Logf("Row %d: id=%s, id*2=%s ✓", i, idVal, doubledVal)
  392. }
  393. }
  394. }
  395. })
  396. }
  397. // TestSQLEngine_OFFSET_WithAggregation tests OFFSET with aggregation queries
  398. func TestSQLEngine_OFFSET_WithAggregation(t *testing.T) {
  399. engine := NewTestSQLEngine()
  400. // Note: Aggregation queries typically return single rows, so OFFSET behavior is different
  401. t.Run("COUNT with OFFSET", func(t *testing.T) {
  402. result, err := engine.ExecuteSQL(context.Background(), "SELECT COUNT(*) FROM user_events LIMIT 1 OFFSET 0")
  403. if err != nil {
  404. t.Fatalf("Expected no error, got %v", err)
  405. }
  406. if result.Error != nil {
  407. t.Fatalf("Expected no query error, got %v", result.Error)
  408. }
  409. // COUNT typically returns 1 row, so OFFSET 0 should return that row
  410. if len(result.Rows) != 1 {
  411. t.Errorf("Expected 1 row for COUNT with OFFSET 0, got %d", len(result.Rows))
  412. }
  413. })
  414. t.Run("COUNT with OFFSET 1", func(t *testing.T) {
  415. result, err := engine.ExecuteSQL(context.Background(), "SELECT COUNT(*) FROM user_events LIMIT 1 OFFSET 1")
  416. if err != nil {
  417. t.Fatalf("Expected no error, got %v", err)
  418. }
  419. if result.Error != nil {
  420. t.Fatalf("Expected no query error, got %v", result.Error)
  421. }
  422. // COUNT returns 1 row, so OFFSET 1 should return 0 rows
  423. if len(result.Rows) != 0 {
  424. t.Errorf("Expected 0 rows for COUNT with OFFSET 1, got %d", len(result.Rows))
  425. }
  426. })
  427. }