tx_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. package storage
  2. import (
  3. "fmt"
  4. "sync"
  5. "testing"
  6. "time"
  7. )
  8. func newTestSession(t *testing.T) (*testKVServer, *KVPool, *SchemaManager, *TableManager) {
  9. t.Helper()
  10. kv := newTestKVServer(t)
  11. pool := newTestKVPool(kv, 8, 5*time.Second)
  12. schemas := NewSchemaManager(pool, "testdb")
  13. tables := NewTableManager(pool, schemas, "testdb")
  14. t.Cleanup(func() { pool.Close() })
  15. return kv, pool, schemas, tables
  16. }
  17. func createTestTable(t *testing.T, schemas *SchemaManager, name string, cols []Column) {
  18. t.Helper()
  19. if err := schemas.CreateTable(&Schema{Name: name, Columns: cols}); err != nil {
  20. t.Fatalf("create table %s: %v", name, err)
  21. }
  22. }
  23. func TestSessionReadYourWrites(t *testing.T) {
  24. _, _, schemas, tables := newTestSession(t)
  25. createTestTable(t, schemas, "t", []Column{{Name: "id", Type: "INTEGER", PrimaryKey: true}, {Name: "v", Type: "TEXT"}})
  26. s := NewSession(schemas, tables)
  27. if err := s.Begin(); err != nil {
  28. t.Fatal(err)
  29. }
  30. if err := s.Insert("t", Row{"id": int64(1), "v": "one"}); err != nil {
  31. t.Fatal(err)
  32. }
  33. // Point read observes the staged overlay before commit.
  34. row, err := s.GetByPK("t", "1")
  35. if err != nil || row["v"] != "one" {
  36. t.Fatalf("read-your-writes GetByPK: row=%v err=%v", row, err)
  37. }
  38. // Scan observes the staged overlay before commit.
  39. rows, err := s.Select("t", nil)
  40. if err != nil || len(rows) != 1 || rows[0]["v"] != "one" {
  41. t.Fatalf("read-your-writes Select: rows=%v err=%v", rows, err)
  42. }
  43. if err := s.Commit(); err != nil {
  44. t.Fatal(err)
  45. }
  46. // Still visible from a fresh read after commit.
  47. if row, err := tables.GetByPK("t", "1"); err != nil || row["v"] != "one" {
  48. t.Fatalf("post-commit GetByPK: row=%v err=%v", row, err)
  49. }
  50. }
  51. func TestSessionIndexedReadTracksOnlyMatches(t *testing.T) {
  52. _, _, schemas, tables := newTestSession(t)
  53. createTestTable(t, schemas, "items", []Column{
  54. {Name: "id", Type: "INTEGER", PrimaryKey: true},
  55. {Name: "cart_id", Type: "TEXT"},
  56. })
  57. if err := schemas.CreateIndex(&Index{
  58. Name: "idx_items_cart", Table: "items",
  59. Columns: []IndexColumn{{Name: "cart_id"}},
  60. }); err != nil {
  61. t.Fatal(err)
  62. }
  63. rows := make([]Row, 50)
  64. for i := range rows {
  65. rows[i] = Row{"id": int64(i + 1), "cart_id": fmt.Sprintf("cart-%d", i)}
  66. }
  67. if _, err := tables.InsertBulk("items", rows); err != nil {
  68. t.Fatal(err)
  69. }
  70. if err := tables.BuildIndex("idx_items_cart", "items", []string{"cart_id"}); err != nil {
  71. t.Fatal(err)
  72. }
  73. s := NewSession(schemas, tables)
  74. if err := s.Begin(); err != nil {
  75. t.Fatal(err)
  76. }
  77. got, err := s.SelectByIndex("items", "idx_items_cart", "cart-37")
  78. if err != nil {
  79. t.Fatal(err)
  80. }
  81. if len(got) != 1 || got[0]["id"] != int64(38) {
  82. t.Fatalf("indexed rows = %#v", got)
  83. }
  84. if len(s.reads) != 1 {
  85. t.Fatalf("indexed transaction captured %d row versions, want 1", len(s.reads))
  86. }
  87. if err := s.Rollback(); err != nil {
  88. t.Fatal(err)
  89. }
  90. }
  91. func TestSessionIndexedPredicateConflictsOnlyOnMatchingValue(t *testing.T) {
  92. _, _, schemas, tables := newTestSession(t)
  93. createTestTable(t, schemas, "items", []Column{
  94. {Name: "id", Type: "INTEGER", PrimaryKey: true},
  95. {Name: "cart_id", Type: "TEXT"},
  96. })
  97. if err := schemas.CreateIndex(&Index{
  98. Name: "idx_items_cart", Table: "items",
  99. Columns: []IndexColumn{{Name: "cart_id"}},
  100. }); err != nil {
  101. t.Fatal(err)
  102. }
  103. if err := tables.Insert("items", Row{"id": int64(1), "cart_id": "cart-a"}); err != nil {
  104. t.Fatal(err)
  105. }
  106. if err := tables.BuildIndex("idx_items_cart", "items", []string{"cart_id"}); err != nil {
  107. t.Fatal(err)
  108. }
  109. unrelated := NewSession(schemas, tables)
  110. if err := unrelated.Begin(); err != nil {
  111. t.Fatal(err)
  112. }
  113. if _, err := unrelated.SelectByIndex("items", "idx_items_cart", "cart-a"); err != nil {
  114. t.Fatal(err)
  115. }
  116. if err := tables.Insert("items", Row{"id": int64(2), "cart_id": "cart-b"}); err != nil {
  117. t.Fatal(err)
  118. }
  119. if err := unrelated.Commit(); err != nil {
  120. t.Fatalf("unrelated indexed insert caused conflict: %v", err)
  121. }
  122. matching := NewSession(schemas, tables)
  123. if err := matching.Begin(); err != nil {
  124. t.Fatal(err)
  125. }
  126. if _, err := matching.SelectByIndex("items", "idx_items_cart", "cart-c"); err != nil {
  127. t.Fatal(err)
  128. }
  129. if err := tables.Insert("items", Row{"id": int64(3), "cart_id": "cart-c"}); err != nil {
  130. t.Fatal(err)
  131. }
  132. if err := matching.Commit(); err != ErrSerialization {
  133. t.Fatalf("matching indexed insert commit error = %v, want ErrSerialization", err)
  134. }
  135. }
  136. func TestSessionRollbackZeroDurableWrites(t *testing.T) {
  137. kv, _, schemas, tables := newTestSession(t)
  138. createTestTable(t, schemas, "t", []Column{{Name: "id", Type: "INTEGER", PrimaryKey: true}})
  139. s := NewSession(schemas, tables)
  140. if err := s.Begin(); err != nil {
  141. t.Fatal(err)
  142. }
  143. if err := s.Insert("t", Row{"id": int64(1)}); err != nil {
  144. t.Fatal(err)
  145. }
  146. if _, deleted, err := s.DeleteByPK("t", "1"); err != nil || !deleted {
  147. t.Fatalf("delete staged row: deleted=%v err=%v", deleted, err)
  148. }
  149. if err := s.Insert("t", Row{"id": int64(2)}); err != nil {
  150. t.Fatal(err)
  151. }
  152. if err := s.Rollback(); err != nil {
  153. t.Fatal(err)
  154. }
  155. if got := kv.countKeys("testdb:_data:t:"); got != 0 {
  156. t.Fatalf("rollback left %d durable rows", got)
  157. }
  158. }
  159. func TestSessionSavepoints(t *testing.T) {
  160. _, _, schemas, tables := newTestSession(t)
  161. createTestTable(t, schemas, "t", []Column{{Name: "id", Type: "INTEGER", PrimaryKey: true}})
  162. s := NewSession(schemas, tables)
  163. if err := s.Begin(); err != nil {
  164. t.Fatal(err)
  165. }
  166. if err := s.Insert("t", Row{"id": int64(1)}); err != nil {
  167. t.Fatal(err)
  168. }
  169. sp := s.Snapshot()
  170. if err := s.Insert("t", Row{"id": int64(2)}); err != nil {
  171. t.Fatal(err)
  172. }
  173. s.RollbackTo(sp)
  174. if err := s.Commit(); err != nil {
  175. t.Fatal(err)
  176. }
  177. if _, err := tables.GetByPK("t", "1"); err != nil {
  178. t.Fatalf("row 1 should be committed: %v", err)
  179. }
  180. if _, err := tables.GetByPK("t", "2"); err != ErrKeyNotFound {
  181. t.Fatalf("row 2 should be discarded, err=%v", err)
  182. }
  183. }
  184. func TestSessionAtomicMultiTableCommit(t *testing.T) {
  185. _, _, schemas, tables := newTestSession(t)
  186. createTestTable(t, schemas, "a", []Column{{Name: "id", Type: "INTEGER", PrimaryKey: true}})
  187. createTestTable(t, schemas, "b", []Column{{Name: "id", Type: "INTEGER", PrimaryKey: true}})
  188. s1 := NewSession(schemas, tables)
  189. s2 := NewSession(schemas, tables)
  190. if err := s1.Begin(); err != nil {
  191. t.Fatal(err)
  192. }
  193. if err := s2.Begin(); err != nil {
  194. t.Fatal(err)
  195. }
  196. if err := s1.Insert("a", Row{"id": int64(1)}); err != nil {
  197. t.Fatal(err)
  198. }
  199. if err := s1.Insert("b", Row{"id": int64(1)}); err != nil {
  200. t.Fatal(err)
  201. }
  202. if err := s2.Insert("a", Row{"id": int64(1)}); err != nil {
  203. t.Fatal(err)
  204. }
  205. if err := s2.Insert("b", Row{"id": int64(2)}); err != nil {
  206. t.Fatal(err)
  207. }
  208. if err := s1.Commit(); err != nil {
  209. t.Fatal(err)
  210. }
  211. if err := s2.Commit(); err != ErrSerialization {
  212. t.Fatalf("expected s2 commit to conflict, got %v", err)
  213. }
  214. // s1 committed both rows; s2 committed neither (atomic rollback).
  215. if _, err := tables.GetByPK("a", "1"); err != nil {
  216. t.Fatalf("a/1 missing: %v", err)
  217. }
  218. if _, err := tables.GetByPK("b", "1"); err != nil {
  219. t.Fatalf("b/1 missing: %v", err)
  220. }
  221. if _, err := tables.GetByPK("b", "2"); err != ErrKeyNotFound {
  222. t.Fatalf("b/2 should be absent after s2 conflict, err=%v", err)
  223. }
  224. }
  225. func TestSessionConflictingUpdateExactlyOneCommits(t *testing.T) {
  226. _, _, schemas, tables := newTestSession(t)
  227. createTestTable(t, schemas, "acct", []Column{{Name: "id", Type: "INTEGER", PrimaryKey: true}, {Name: "bal", Type: "INTEGER"}})
  228. if err := tables.Insert("acct", Row{"id": int64(1), "bal": int64(100)}); err != nil {
  229. t.Fatal(err)
  230. }
  231. s1 := NewSession(schemas, tables)
  232. s2 := NewSession(schemas, tables)
  233. update := func(s *Session) (func() error, error) {
  234. if err := s.Begin(); err != nil {
  235. return nil, err
  236. }
  237. row, err := s.GetByPK("acct", "1")
  238. if err != nil {
  239. return nil, err
  240. }
  241. if _, _, err := s.UpdateByPK("acct", "1", func(Row) (Row, error) {
  242. return Row{"bal": row["bal"].(int64) + 10}, nil
  243. }); err != nil {
  244. return nil, err
  245. }
  246. return s.Commit, nil
  247. }
  248. c1, err := update(s1)
  249. if err != nil {
  250. t.Fatal(err)
  251. }
  252. c2, err := update(s2)
  253. if err != nil {
  254. t.Fatal(err)
  255. }
  256. errs := make([]error, 2)
  257. var wg sync.WaitGroup
  258. wg.Add(2)
  259. go func() { defer wg.Done(); errs[0] = c1() }()
  260. go func() { defer wg.Done(); errs[1] = c2() }()
  261. wg.Wait()
  262. ok, conflict := 0, 0
  263. for _, e := range errs {
  264. if e == nil {
  265. ok++
  266. } else if e == ErrSerialization {
  267. conflict++
  268. } else {
  269. t.Fatalf("unexpected commit error: %v", e)
  270. }
  271. }
  272. if ok != 1 || conflict != 1 {
  273. t.Fatalf("expected exactly one commit and one conflict, got ok=%d conflict=%d", ok, conflict)
  274. }
  275. row, err := tables.GetByPK("acct", "1")
  276. if err != nil || row["bal"] != int64(110) {
  277. t.Fatalf("balance should be 110, got %v err=%v", row, err)
  278. }
  279. }
  280. func TestSessionNonConflictingConcurrentTransactions(t *testing.T) {
  281. _, _, schemas, tables := newTestSession(t)
  282. createTestTable(t, schemas, "t", []Column{{Name: "id", Type: "INTEGER", PrimaryKey: true}, {Name: "v", Type: "TEXT"}})
  283. s1 := NewSession(schemas, tables)
  284. s2 := NewSession(schemas, tables)
  285. if err := s1.Begin(); err != nil {
  286. t.Fatal(err)
  287. }
  288. if err := s2.Begin(); err != nil {
  289. t.Fatal(err)
  290. }
  291. if err := s1.Insert("t", Row{"id": int64(1), "v": "a"}); err != nil {
  292. t.Fatal(err)
  293. }
  294. if err := s2.Insert("t", Row{"id": int64(2), "v": "b"}); err != nil {
  295. t.Fatal(err)
  296. }
  297. var wg sync.WaitGroup
  298. errs := make([]error, 2)
  299. wg.Add(2)
  300. go func() { defer wg.Done(); errs[0] = s1.Commit() }()
  301. go func() { defer wg.Done(); errs[1] = s2.Commit() }()
  302. wg.Wait()
  303. for i, e := range errs {
  304. if e != nil {
  305. t.Fatalf("commit %d failed: %v", i, e)
  306. }
  307. }
  308. if rows, err := tables.Select("t", nil); err != nil || len(rows) != 2 {
  309. t.Fatalf("expected 2 rows, got %d err=%v", len(rows), err)
  310. }
  311. }
  312. func TestDuplicateInsertConcurrent(t *testing.T) {
  313. _, _, schemas, tables := newTestSession(t)
  314. createTestTable(t, schemas, "t", []Column{{Name: "id", Type: "INTEGER", PrimaryKey: true}})
  315. const n = 32
  316. errs := make([]error, n)
  317. var wg sync.WaitGroup
  318. for i := 0; i < n; i++ {
  319. wg.Add(1)
  320. go func() {
  321. defer wg.Done()
  322. errs[i] = tables.Insert("t", Row{"id": int64(1)})
  323. }()
  324. }
  325. wg.Wait()
  326. ok := 0
  327. for _, e := range errs {
  328. if e == nil {
  329. ok++
  330. } else if !(e != nil && fmt.Sprintf("%s", e) == "duplicate primary key: 1") {
  331. t.Fatalf("unexpected insert error: %v", e)
  332. }
  333. }
  334. if ok != 1 {
  335. t.Fatalf("expected exactly one successful insert, got %d", ok)
  336. }
  337. if got := kvCount(t, tables, "t"); got != 1 {
  338. t.Fatalf("expected 1 row, got %d", got)
  339. }
  340. }
  341. func kvCount(t *testing.T, tables *TableManager, table string) int {
  342. t.Helper()
  343. n, err := tables.CountFast(table)
  344. if err != nil {
  345. t.Fatal(err)
  346. }
  347. return n
  348. }
  349. func TestPerTableConcurrentRowIDs(t *testing.T) {
  350. _, _, schemas, tables := newTestSession(t)
  351. createTestTable(t, schemas, "t", []Column{{Name: "name", Type: "TEXT"}}) // _rowid_ PK
  352. const n = 100
  353. var wg sync.WaitGroup
  354. errCh := make(chan error, n)
  355. for i := 0; i < n; i++ {
  356. wg.Add(1)
  357. go func(i int) {
  358. defer wg.Done()
  359. if err := tables.Insert("t", Row{"name": fmt.Sprintf("n%d", i)}); err != nil {
  360. errCh <- fmt.Errorf("insert %d: %v", i, err)
  361. }
  362. }(i)
  363. }
  364. wg.Wait()
  365. close(errCh)
  366. for err := range errCh {
  367. t.Fatal(err)
  368. }
  369. if rows, err := tables.Select("t", nil); err != nil || len(rows) != n {
  370. t.Fatalf("expected %d rows, got %d err=%v", n, len(rows), err)
  371. }
  372. }
  373. func TestPointOpsDifferentKeysProgressConcurrently(t *testing.T) {
  374. _, _, schemas, tables := newTestSession(t)
  375. createTestTable(t, schemas, "t", []Column{{Name: "id", Type: "TEXT", PrimaryKey: true}, {Name: "v", Type: "INTEGER"}})
  376. const n = 50
  377. var wg sync.WaitGroup
  378. errCh := make(chan error, n*3)
  379. for i := 0; i < n; i++ {
  380. wg.Add(1)
  381. go func(i int) {
  382. defer wg.Done()
  383. key := fmt.Sprintf("k%d", i)
  384. if err := tables.Insert("t", Row{"id": key, "v": int64(i)}); err != nil {
  385. errCh <- fmt.Errorf("insert %s: %v", key, err)
  386. return
  387. }
  388. if _, _, err := tables.UpdateByPK("t", key, func(Row) (Row, error) { return Row{"v": int64(i + 100)}, nil }); err != nil {
  389. errCh <- fmt.Errorf("update %s: %v", key, err)
  390. return
  391. }
  392. if _, err := tables.GetByPK("t", key); err != nil {
  393. errCh <- fmt.Errorf("get %s: %v", key, err)
  394. }
  395. }(i)
  396. }
  397. done := make(chan struct{})
  398. go func() { wg.Wait(); close(done) }()
  399. select {
  400. case <-done:
  401. case <-time.After(10 * time.Second):
  402. t.Fatal("point operations on distinct keys did not progress concurrently")
  403. }
  404. close(errCh)
  405. for err := range errCh {
  406. t.Fatal(err)
  407. }
  408. }