tx.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  1. package storage
  2. import (
  3. "fmt"
  4. "sort"
  5. "strings"
  6. "sync"
  7. )
  8. // ErrSerialization is returned when a transaction's optimistic validation fails
  9. // because a concurrent transaction committed a conflicting change.
  10. var ErrSerialization = fmt.Errorf("serialization failure: concurrent transaction modified the database")
  11. // Session is a buffered SQL transaction/session wrapper around a TableManager.
  12. // While in a transaction, writes are staged in memory, reads observe that
  13. // staged overlay, and COMMIT issues a single atomic compare-and-swap batch
  14. // write. Rollback simply discards the staged changes (no compensating durable
  15. // writes). A Session is used for both autocommit statements (where operations
  16. // delegate straight to the durable TableManager) and buffered transactions.
  17. type Session struct {
  18. schema *SchemaManager
  19. table *TableManager
  20. mu sync.Mutex
  21. inTx bool
  22. aborted bool
  23. // overlay holds staged writes keyed by lowercased table then data key.
  24. overlay map[string]map[string]*overlayEntry
  25. // log records mutations in order so savepoints can roll back.
  26. log []txMutation
  27. // reads records the durable LSN of every key the transaction observed
  28. // (0 means the key was observed absent). It becomes the compare set at
  29. // commit and also captures the base LSN of every written key.
  30. reads map[string]uint64
  31. // scanGens records the per-table generation captured by the first scan of
  32. // each table, validated at commit to detect phantoms. Indexed equality reads
  33. // use predicateGens so writes to other index values do not cause conflicts.
  34. scanGens map[string]uint64
  35. predicateGens map[string]predicateRead
  36. }
  37. type predicateRead struct {
  38. table string
  39. gen uint64
  40. }
  41. type overlayEntry struct {
  42. row Row
  43. absent bool
  44. }
  45. type txMutation struct {
  46. table string
  47. key string
  48. prev *overlayEntry
  49. }
  50. // NewSession creates a session wrapping the given schema and table managers.
  51. func NewSession(schema *SchemaManager, table *TableManager) *Session {
  52. return &Session{
  53. schema: schema,
  54. table: table,
  55. overlay: make(map[string]map[string]*overlayEntry),
  56. reads: make(map[string]uint64),
  57. scanGens: make(map[string]uint64),
  58. predicateGens: make(map[string]predicateRead),
  59. }
  60. }
  61. // Begin starts a buffered transaction.
  62. func (s *Session) Begin() error {
  63. s.mu.Lock()
  64. defer s.mu.Unlock()
  65. if s.inTx {
  66. return fmt.Errorf("cannot start a transaction within a transaction")
  67. }
  68. s.inTx = true
  69. s.aborted = false
  70. s.overlay = make(map[string]map[string]*overlayEntry)
  71. s.log = nil
  72. s.reads = make(map[string]uint64)
  73. s.scanGens = make(map[string]uint64)
  74. s.predicateGens = make(map[string]predicateRead)
  75. return nil
  76. }
  77. // InTx reports whether a transaction is in progress.
  78. func (s *Session) InTx() bool {
  79. s.mu.Lock()
  80. defer s.mu.Unlock()
  81. return s.inTx
  82. }
  83. // Abort marks the transaction as aborted without discarding state.
  84. func (s *Session) Abort() {
  85. s.mu.Lock()
  86. defer s.mu.Unlock()
  87. if s.inTx {
  88. s.aborted = true
  89. }
  90. }
  91. // Snapshot returns the current mutation-log position for a savepoint.
  92. func (s *Session) Snapshot() int {
  93. s.mu.Lock()
  94. defer s.mu.Unlock()
  95. return len(s.log)
  96. }
  97. // RollbackTo discards mutations after the given savepoint position.
  98. func (s *Session) RollbackTo(pos int) {
  99. s.mu.Lock()
  100. defer s.mu.Unlock()
  101. for i := len(s.log) - 1; i >= pos && i >= 0; i-- {
  102. m := s.log[i]
  103. if m.prev == nil {
  104. delete(s.overlay[m.table], m.key)
  105. if len(s.overlay[m.table]) == 0 {
  106. delete(s.overlay, m.table)
  107. }
  108. } else {
  109. if s.overlay[m.table] == nil {
  110. s.overlay[m.table] = make(map[string]*overlayEntry)
  111. }
  112. s.overlay[m.table][m.key] = m.prev
  113. }
  114. }
  115. if pos < len(s.log) {
  116. s.log = s.log[:pos]
  117. }
  118. s.aborted = false
  119. }
  120. // Rollback discards the transaction without writing anything durable.
  121. func (s *Session) Rollback() error {
  122. s.mu.Lock()
  123. defer s.mu.Unlock()
  124. if !s.inTx {
  125. return fmt.Errorf("cannot rollback: no transaction in progress")
  126. }
  127. s.resetLocked()
  128. return nil
  129. }
  130. // Commit validates and durably applies the staged transaction in one atomic
  131. // compare-and-swap batch write. It discards the commit LSN; callers that need a
  132. // ordering cursor use CommitWithLSN.
  133. func (s *Session) Commit() error {
  134. _, err := s.CommitWithLSN()
  135. return err
  136. }
  137. // CommitWithLSN behaves like Commit and additionally returns the LSN assigned
  138. // to the durable batch. A read-only or empty transaction returns zero because
  139. // no new durable state was published.
  140. func (s *Session) CommitWithLSN() (uint64, error) {
  141. s.mu.Lock()
  142. defer s.mu.Unlock()
  143. if !s.inTx {
  144. return 0, fmt.Errorf("cannot commit: no transaction in progress")
  145. }
  146. if s.aborted {
  147. s.resetLocked()
  148. return 0, fmt.Errorf("current transaction is aborted")
  149. }
  150. // Acquire the per-table gates, escalating any table whose UNIQUE index
  151. // appeared after the initial unlocked probe. See acquireCommitLocks.
  152. _, _, unlockAll, uniqueTables, err := s.acquireCommitLocks()
  153. if err != nil {
  154. s.resetLocked()
  155. return 0, err
  156. }
  157. defer unlockAll()
  158. // Validate scan generations for phantom detection.
  159. for t, gen := range s.scanGens {
  160. if s.table.generation(t) != gen {
  161. s.resetLocked()
  162. return 0, ErrSerialization
  163. }
  164. }
  165. for key, predicate := range s.predicateGens {
  166. if s.table.predicateGeneration(key) != predicate.gen {
  167. s.resetLocked()
  168. return 0, ErrSerialization
  169. }
  170. }
  171. // Validate the final overlay of every unique-indexed written table against
  172. // durable rows. This runs under the exclusive gate acquired above, so it
  173. // cannot race a concurrent writer. Duplicate unique values fail the commit
  174. // with a "UNIQUE constraint failed" error rather than ErrSerialization.
  175. uniquePlans := make(map[string]uniqueCachePlan, len(uniqueTables))
  176. for t := range uniqueTables {
  177. plan, err := s.table.prepareUniqueRows(t, s.overlay[t])
  178. if err != nil {
  179. s.resetLocked()
  180. return 0, err
  181. }
  182. uniquePlans[t] = plan
  183. }
  184. exclusiveTables := make(map[string]bool)
  185. for table := range uniqueTables {
  186. exclusiveTables[table] = true
  187. }
  188. for table := range s.scanGens {
  189. exclusiveTables[table] = true
  190. }
  191. for _, predicate := range s.predicateGens {
  192. exclusiveTables[predicate.table] = true
  193. }
  194. cachePlans := make(map[string]*tableCachePlan)
  195. for table, entries := range s.overlay {
  196. if exclusiveTables[table] {
  197. plan, err := s.table.prepareTableCache(table, entries, s.reads)
  198. if err != nil {
  199. s.resetLocked()
  200. return 0, err
  201. }
  202. cachePlans[table] = plan
  203. }
  204. }
  205. // Build the compare set from every observed key.
  206. checks := make([]CompareCheck, 0, len(s.reads))
  207. for key, lsn := range s.reads {
  208. checks = append(checks, CompareCheck{Key: []byte(key), LSN: lsn})
  209. }
  210. sort.Slice(checks, func(i, j int) bool { return string(checks[i].Key) < string(checks[j].Key) })
  211. // Build the batch ops from the staged overlay.
  212. ops := make([]BatchOp, 0)
  213. for _, entries := range s.overlay {
  214. for key, e := range entries {
  215. if e.absent {
  216. ops = append(ops, BatchOp{Op: batchDelete, Key: []byte(key)})
  217. } else {
  218. data, err := encodeRow(e.row)
  219. if err != nil {
  220. s.resetLocked()
  221. return 0, err
  222. }
  223. ops = append(ops, BatchOp{Op: batchPut, Key: []byte(key), Value: data})
  224. }
  225. }
  226. }
  227. sort.Slice(ops, func(i, j int) bool { return string(ops[i].Key) < string(ops[j].Key) })
  228. // A read-only transaction has nothing to write; commit trivially.
  229. if len(ops) == 0 {
  230. s.resetLocked()
  231. return 0, nil
  232. }
  233. var committed bool
  234. var commitLSN uint64
  235. err = s.table.pool.WithClient(func(c *KVClient) error {
  236. lsn, ok, err := c.CompareBatchWrite(checks, ops, nil)
  237. commitLSN = lsn
  238. committed = ok
  239. return err
  240. })
  241. if err != nil || !committed {
  242. // A transport error can hide a durable commit; a compare conflict can
  243. // also expose an out-of-band writer. Rebuild derived state next time.
  244. for table := range s.overlay {
  245. s.table.invalidateWriteFailure(table)
  246. }
  247. }
  248. if err != nil {
  249. s.resetLocked()
  250. return 0, err
  251. }
  252. if !committed {
  253. s.resetLocked()
  254. return 0, ErrSerialization
  255. }
  256. // Publish derived state before generations while retaining the table gates.
  257. for t := range s.overlay {
  258. if plan := cachePlans[t]; plan != nil {
  259. s.table.applyTableCache(plan)
  260. } else {
  261. s.table.invalidateCache(t)
  262. }
  263. s.table.applyUniquePlan(uniquePlans[t], nil)
  264. s.table.bumpIndexPredicateWildcard(t)
  265. s.table.bumpGeneration(t)
  266. }
  267. s.resetLocked()
  268. return commitLSN, nil
  269. }
  270. // acquireCommitLocks acquires the per-table gates needed to commit the staged
  271. // transaction, returning the held locks, whether each is exclusive, an unlock
  272. // function, and the set of written tables that carry a UNIQUE index. A written
  273. // table with a UNIQUE index is locked exclusively so its final overlay can be
  274. // validated against durable rows. The uniqueness probe is re-checked under the
  275. // held gates so a concurrent CREATE UNIQUE INDEX cannot slip in after the probe
  276. // and leave a duplicate unvalidated.
  277. func (s *Session) acquireCommitLocks() (locks []*sync.RWMutex, exclusive []bool, unlockAll func(), uniqueTables map[string]bool, err error) {
  278. unlock := func(ls []*sync.RWMutex, ex []bool) {
  279. for i := len(ls) - 1; i >= 0; i-- {
  280. if ex[i] {
  281. ls[i].Unlock()
  282. } else {
  283. ls[i].RUnlock()
  284. }
  285. }
  286. }
  287. for {
  288. // Tables read through scans or predicates need an exclusive validation
  289. // gate. Tables that are only written use the shared publication gate,
  290. // allowing disjoint optimistic commits to proceed concurrently while
  291. // still excluding scanner commits.
  292. affected := make(map[string]bool)
  293. for t := range s.overlay {
  294. affected[t] = false
  295. }
  296. for t := range s.scanGens {
  297. affected[t] = true
  298. }
  299. for _, predicate := range s.predicateGens {
  300. affected[predicate.table] = true
  301. }
  302. // Tables written in this transaction that carry a UNIQUE index need the
  303. // exclusive gate so their final overlay can be validated against durable
  304. // rows without racing another writer.
  305. uniqueTables = make(map[string]bool)
  306. for t := range s.overlay {
  307. uniq, err := s.table.hasUniqueIndex(t)
  308. if err != nil {
  309. return nil, nil, nil, nil, err
  310. }
  311. if uniq {
  312. uniqueTables[t] = true
  313. affected[t] = true
  314. }
  315. }
  316. tables := make([]string, 0, len(affected))
  317. for t := range affected {
  318. tables = append(tables, t)
  319. }
  320. sort.Strings(tables)
  321. locks = make([]*sync.RWMutex, len(tables))
  322. exclusive = make([]bool, len(tables))
  323. for i, t := range tables {
  324. locks[i] = s.table.tableLock(t)
  325. exclusive[i] = affected[t]
  326. }
  327. for i, lock := range locks {
  328. if exclusive[i] {
  329. lock.Lock()
  330. } else {
  331. lock.RLock()
  332. }
  333. }
  334. // Re-check under the held gates. A concurrent CREATE UNIQUE INDEX can
  335. // only have completed before we acquired the gate (it needs the exclusive
  336. // gate), so this probe is authoritative; escalate and retry if a written
  337. // table gained a unique index.
  338. retry := false
  339. for i, t := range tables {
  340. if exclusive[i] {
  341. continue
  342. }
  343. if _, written := s.overlay[t]; !written {
  344. continue
  345. }
  346. uniq, err := s.table.hasUniqueIndex(t)
  347. if err != nil {
  348. unlock(locks, exclusive)
  349. return nil, nil, nil, nil, err
  350. }
  351. if uniq {
  352. retry = true
  353. break
  354. }
  355. }
  356. if retry {
  357. unlock(locks, exclusive)
  358. continue
  359. }
  360. unlockAll = func() { unlock(locks, exclusive) }
  361. return locks, exclusive, unlockAll, uniqueTables, nil
  362. }
  363. }
  364. func (s *Session) resetLocked() {
  365. s.inTx = false
  366. s.aborted = false
  367. s.overlay = make(map[string]map[string]*overlayEntry)
  368. s.log = nil
  369. s.reads = make(map[string]uint64)
  370. s.scanGens = make(map[string]uint64)
  371. s.predicateGens = make(map[string]predicateRead)
  372. }
  373. func (s *Session) stagePut(table, key string, row Row) {
  374. tl := strings.ToLower(table)
  375. if s.overlay[tl] == nil {
  376. s.overlay[tl] = make(map[string]*overlayEntry)
  377. }
  378. s.log = append(s.log, txMutation{table: tl, key: key, prev: s.overlay[tl][key]})
  379. s.overlay[tl][key] = &overlayEntry{row: cloneRow(row)}
  380. if _, ok := s.reads[key]; !ok {
  381. s.reads[key] = 0
  382. }
  383. }
  384. func (s *Session) stageDelete(table, key string, row Row) {
  385. tl := strings.ToLower(table)
  386. if s.overlay[tl] == nil {
  387. s.overlay[tl] = make(map[string]*overlayEntry)
  388. }
  389. s.log = append(s.log, txMutation{table: tl, key: key, prev: s.overlay[tl][key]})
  390. // Keep the deleted row so COMMIT can exempt its rowid from the unique-index
  391. // scan and release its unique value.
  392. s.overlay[tl][key] = &overlayEntry{row: cloneRow(row), absent: true}
  393. if _, ok := s.reads[key]; !ok {
  394. s.reads[key] = 0
  395. }
  396. }
  397. // GetByPK retrieves a row by primary key, observing the staged overlay in a
  398. // transaction and recording the observed LSN for validation.
  399. func (s *Session) GetByPK(table, pk string) (Row, error) {
  400. s.mu.Lock()
  401. defer s.mu.Unlock()
  402. if !s.inTx {
  403. return s.table.GetByPK(table, pk)
  404. }
  405. key := s.table.dataKey(table, pk)
  406. tl := strings.ToLower(table)
  407. if e, ok := s.overlay[tl][key]; ok {
  408. if e.absent {
  409. return nil, ErrKeyNotFound
  410. }
  411. return cloneRow(e.row), nil
  412. }
  413. row, lsn, err := s.table.getByPKWithLSN(table, pk)
  414. if err != nil {
  415. if err == ErrKeyNotFound {
  416. s.reads[key] = 0
  417. return nil, ErrKeyNotFound
  418. }
  419. return nil, err
  420. }
  421. s.reads[key] = lsn
  422. return row, nil
  423. }
  424. // Select scans a table, merging the staged overlay so a transaction sees its
  425. // own writes, and records per-row LSNs plus the table generation.
  426. func (s *Session) Select(table string, filter func(Row) bool) ([]Row, error) {
  427. s.mu.Lock()
  428. if !s.inTx {
  429. s.mu.Unlock()
  430. return s.table.Select(table, filter)
  431. }
  432. defer s.mu.Unlock()
  433. return s.selectLocked(table, filter)
  434. }
  435. // SelectLimited bounds an autocommit scan. Explicit transactions retain the
  436. // complete overlay/read-set behavior until bounded transactional scans have a
  437. // separate phantom/overlay contract; their caller still applies LIMIT later.
  438. func (s *Session) SelectLimited(table string, filter func(Row) bool, maxRows int) ([]Row, error) {
  439. s.mu.Lock()
  440. if s.inTx {
  441. defer s.mu.Unlock()
  442. return s.selectLocked(table, filter)
  443. }
  444. s.mu.Unlock()
  445. if maxRows == 0 {
  446. return []Row{}, nil
  447. }
  448. return s.table.SelectWithLimit(table, filter, maxRows, 0)
  449. }
  450. func (s *Session) selectLocked(table string, filter func(Row) bool) ([]Row, error) {
  451. schema, err := s.schema.GetSchema(table)
  452. if err != nil {
  453. return nil, err
  454. }
  455. tl := strings.ToLower(table)
  456. tableLock := s.table.tableLock(tl)
  457. tableLock.RLock()
  458. defer tableLock.RUnlock()
  459. if _, ok := s.scanGens[tl]; !ok {
  460. s.scanGens[tl] = s.table.generation(tl)
  461. }
  462. overlay := s.overlay[tl]
  463. var rows []Row
  464. err = s.table.scanRowsWithLSN(table, func(row Row, lsn uint64) (bool, error) {
  465. key := s.table.dataKey(table, fmt.Sprintf("%v", row[schema.PrimaryKey]))
  466. if _, ok := overlay[key]; ok {
  467. return false, nil
  468. }
  469. s.reads[key] = lsn
  470. if filter == nil || filter(row) {
  471. rows = append(rows, row)
  472. }
  473. return false, nil
  474. })
  475. if err != nil {
  476. return nil, err
  477. }
  478. for _, e := range overlay {
  479. if e.absent {
  480. continue
  481. }
  482. if filter == nil || filter(e.row) {
  483. rows = append(rows, cloneRow(e.row))
  484. }
  485. }
  486. return rows, nil
  487. }
  488. // SelectByIndex reads only matching durable rows while capturing their LSNs,
  489. // then merges the transaction overlay. The table generation protects against
  490. // matching rows being inserted or removed after the lookup.
  491. func (s *Session) SelectByIndex(table, indexName string, colValue interface{}) ([]Row, error) {
  492. s.mu.Lock()
  493. defer s.mu.Unlock()
  494. if !s.inTx {
  495. return s.table.SelectByIndex(table, indexName, colValue)
  496. }
  497. tableKey := strings.ToLower(table)
  498. index, err := s.schema.GetIndex(indexName)
  499. if err != nil {
  500. return nil, err
  501. }
  502. col := index.Columns[0].Name
  503. want := formatIndexValue(colValue)
  504. versions, predicate, err := s.table.selectByIndexWithLSN(table, indexName, colValue)
  505. if err != nil {
  506. return nil, err
  507. }
  508. if _, ok := s.predicateGens[predicate.valueKey]; !ok {
  509. s.predicateGens[predicate.valueKey] = predicateRead{table: tableKey, gen: predicate.valueGen}
  510. }
  511. if _, ok := s.predicateGens[predicate.wildcardKey]; !ok {
  512. s.predicateGens[predicate.wildcardKey] = predicateRead{table: tableKey, gen: predicate.wildcardGen}
  513. }
  514. overlay := s.overlay[tableKey]
  515. rows := make([]Row, 0, len(versions)+len(overlay))
  516. for _, version := range versions {
  517. if _, staged := overlay[version.key]; staged {
  518. continue
  519. }
  520. s.reads[version.key] = version.lsn
  521. rows = append(rows, version.row)
  522. }
  523. for _, entry := range overlay {
  524. if !entry.absent && formatIndexValue(entry.row[col]) == want {
  525. rows = append(rows, cloneRow(entry.row))
  526. }
  527. }
  528. return rows, nil
  529. }
  530. // SelectByIndexKey retrieves the rows whose index key equals valueKey, merging
  531. // the staged overlay so a transaction sees its own writes. valueKey is the
  532. // formatted key from TableManager.IndexRowKey, which supports plain, composite,
  533. // and expression indexes uniformly.
  534. func (s *Session) SelectByIndexKey(table string, idx *Index, valueKey string) ([]Row, error) {
  535. s.mu.Lock()
  536. defer s.mu.Unlock()
  537. if !s.inTx {
  538. versions, _, err := s.table.selectByIndexKeyWithLSN(table, idx.Name, valueKey)
  539. if err != nil {
  540. return nil, err
  541. }
  542. rows := make([]Row, len(versions))
  543. for i := range versions {
  544. rows[i] = versions[i].row
  545. }
  546. return rows, nil
  547. }
  548. tableKey := strings.ToLower(table)
  549. versions, predicate, err := s.table.selectByIndexKeyWithLSN(table, idx.Name, valueKey)
  550. if err != nil {
  551. return nil, err
  552. }
  553. if _, ok := s.predicateGens[predicate.valueKey]; !ok {
  554. s.predicateGens[predicate.valueKey] = predicateRead{table: tableKey, gen: predicate.valueGen}
  555. }
  556. if _, ok := s.predicateGens[predicate.wildcardKey]; !ok {
  557. s.predicateGens[predicate.wildcardKey] = predicateRead{table: tableKey, gen: predicate.wildcardGen}
  558. }
  559. overlay := s.overlay[tableKey]
  560. rows := make([]Row, 0, len(versions)+len(overlay))
  561. for _, version := range versions {
  562. if _, staged := overlay[version.key]; staged {
  563. continue
  564. }
  565. s.reads[version.key] = version.lsn
  566. rows = append(rows, version.row)
  567. }
  568. for _, entry := range overlay {
  569. if entry.absent {
  570. continue
  571. }
  572. key, kerr := s.table.IndexRowKey(idx, entry.row)
  573. if kerr != nil {
  574. return nil, kerr
  575. }
  576. if key == valueKey {
  577. rows = append(rows, cloneRow(entry.row))
  578. }
  579. }
  580. return rows, nil
  581. }
  582. // CountFast returns the exact row count, observing the staged overlay in a
  583. // transaction.
  584. func (s *Session) CountFast(table string) (int, error) {
  585. s.mu.Lock()
  586. defer s.mu.Unlock()
  587. if !s.inTx {
  588. return s.table.CountFast(table)
  589. }
  590. rows, err := s.selectLocked(table, nil)
  591. if err != nil {
  592. return 0, err
  593. }
  594. return len(rows), nil
  595. }
  596. // Insert stages an insert in a transaction, or performs a durable autocommit
  597. // insert otherwise.
  598. func (s *Session) Insert(table string, row Row) error {
  599. _, err := s.InsertWithRowID(table, row)
  600. return err
  601. }
  602. // InsertWithRowID stages an insert in a transaction, or performs a durable
  603. // autocommit insert otherwise, returning the actual generated ROWID.
  604. func (s *Session) InsertWithRowID(table string, row Row) (int64, error) {
  605. s.mu.Lock()
  606. defer s.mu.Unlock()
  607. if !s.inTx {
  608. return s.table.InsertWithRowID(table, row)
  609. }
  610. return s.insertLocked(table, row)
  611. }
  612. // InsertBulk stages or durably bulk-inserts multiple rows.
  613. func (s *Session) InsertBulk(table string, rows []Row) (int, error) {
  614. count, _, err := s.InsertBulkWithLastRowID(table, rows)
  615. return count, err
  616. }
  617. // InsertBulkWithLastRowID is InsertBulk, additionally returning the ROWID of the
  618. // last staged/persisted row (0 when nothing was inserted).
  619. func (s *Session) InsertBulkWithLastRowID(table string, rows []Row) (int, int64, error) {
  620. s.mu.Lock()
  621. defer s.mu.Unlock()
  622. if !s.inTx {
  623. return s.table.InsertBulkWithLastRowID(table, rows)
  624. }
  625. var lastRowID int64
  626. count := 0
  627. for _, row := range rows {
  628. rid, err := s.insertLocked(table, row)
  629. if err != nil {
  630. return count, lastRowID, err
  631. }
  632. lastRowID = rid
  633. count++
  634. }
  635. return count, lastRowID, nil
  636. }
  637. // insertLocked is the transaction insert helper (caller holds s.mu).
  638. func (s *Session) insertLocked(table string, row Row) (int64, error) {
  639. nr, key, err := s.table.prepareInsert(table, row)
  640. if err != nil {
  641. return 0, err
  642. }
  643. rowid, _ := rowIDFromRow(nr)
  644. schema, err := s.schema.GetSchema(table)
  645. if err != nil {
  646. return 0, err
  647. }
  648. pk := fmt.Sprintf("%v", nr[schema.PrimaryKey])
  649. tl := strings.ToLower(table)
  650. if e, ok := s.overlay[tl][key]; ok {
  651. if !e.absent {
  652. return 0, fmt.Errorf("duplicate primary key: %s", pk)
  653. }
  654. } else {
  655. _, lsn, err := s.table.getByPKWithLSN(table, pk)
  656. if err == nil {
  657. s.reads[key] = lsn
  658. return 0, fmt.Errorf("duplicate primary key: %s", pk)
  659. }
  660. if err != ErrKeyNotFound {
  661. return 0, err
  662. }
  663. s.reads[key] = 0
  664. }
  665. s.stagePut(table, key, nr)
  666. return rowid, nil
  667. }
  668. // UpdateByPK stages or durably applies a single-row update.
  669. func (s *Session) UpdateByPK(table, pk string, updateFn func(Row) (Row, error)) (Row, bool, error) {
  670. s.mu.Lock()
  671. if !s.inTx {
  672. s.mu.Unlock()
  673. return s.table.UpdateByPK(table, pk, updateFn)
  674. }
  675. defer s.mu.Unlock()
  676. schema, err := s.schema.GetSchema(table)
  677. if err != nil {
  678. return nil, false, err
  679. }
  680. key := s.table.dataKey(table, pk)
  681. row, err := s.getByPKLocked(table, pk)
  682. if err == ErrKeyNotFound {
  683. return nil, false, nil
  684. }
  685. if err != nil {
  686. return nil, false, err
  687. }
  688. oldRow := cloneRow(row)
  689. updates, err := s.runUpdateFn(updateFn, row)
  690. if err != nil {
  691. return nil, false, err
  692. }
  693. for name, value := range updates {
  694. for _, column := range schema.Columns {
  695. if strings.EqualFold(name, column.Name) {
  696. row[column.Name] = value
  697. break
  698. }
  699. }
  700. }
  701. if err := validateNotNull(schema, row); err != nil {
  702. return nil, false, err
  703. }
  704. s.stagePut(table, key, row)
  705. return oldRow, true, nil
  706. }
  707. // runUpdateFn releases the session lock while invoking the update callback so the
  708. // callback can run nested reads (e.g. a scalar subquery in SET) through the same
  709. // session without deadlocking on s.mu. A connection executes one statement at a
  710. // time, so the staged overlay cannot change while the callback runs. The lock is
  711. // re-acquired before returning.
  712. func (s *Session) runUpdateFn(updateFn func(Row) (Row, error), row Row) (Row, error) {
  713. s.mu.Unlock()
  714. defer s.mu.Lock()
  715. return updateFn(row)
  716. }
  717. // DeleteByPK stages or durably applies a single-row delete.
  718. func (s *Session) DeleteByPK(table, pk string) (Row, bool, error) {
  719. s.mu.Lock()
  720. defer s.mu.Unlock()
  721. if !s.inTx {
  722. return s.table.DeleteByPK(table, pk)
  723. }
  724. key := s.table.dataKey(table, pk)
  725. row, err := s.getByPKLocked(table, pk)
  726. if err == ErrKeyNotFound {
  727. return nil, false, nil
  728. }
  729. if err != nil {
  730. return nil, false, err
  731. }
  732. s.stageDelete(table, key, row)
  733. return row, true, nil
  734. }
  735. // getByPKLocked reads a row observing the overlay (caller holds s.mu).
  736. func (s *Session) getByPKLocked(table, pk string) (Row, error) {
  737. key := s.table.dataKey(table, pk)
  738. tl := strings.ToLower(table)
  739. if e, ok := s.overlay[tl][key]; ok {
  740. if e.absent {
  741. return nil, ErrKeyNotFound
  742. }
  743. return cloneRow(e.row), nil
  744. }
  745. row, lsn, err := s.table.getByPKWithLSN(table, pk)
  746. if err != nil {
  747. if err == ErrKeyNotFound {
  748. s.reads[key] = 0
  749. return nil, ErrKeyNotFound
  750. }
  751. return nil, err
  752. }
  753. s.reads[key] = lsn
  754. return row, nil
  755. }
  756. // UpdateFunc stages or durably applies a scan-based update.
  757. func (s *Session) UpdateFunc(table string, updateFn func(Row) (Row, error), filter func(Row) bool) (int, error) {
  758. s.mu.Lock()
  759. if !s.inTx {
  760. s.mu.Unlock()
  761. return s.table.UpdateFunc(table, updateFn, filter)
  762. }
  763. defer s.mu.Unlock()
  764. schema, err := s.schema.GetSchema(table)
  765. if err != nil {
  766. return 0, err
  767. }
  768. rows, err := s.selectLocked(table, filter)
  769. if err != nil {
  770. return 0, err
  771. }
  772. count := 0
  773. for _, row := range rows {
  774. oldRow := cloneRow(row)
  775. oldKey := s.table.dataKey(table, fmt.Sprintf("%v", row[schema.PrimaryKey]))
  776. updates, err := s.runUpdateFn(updateFn, row)
  777. if err != nil {
  778. return count, err
  779. }
  780. for name, value := range updates {
  781. for _, column := range schema.Columns {
  782. if strings.EqualFold(name, column.Name) {
  783. row[column.Name] = value
  784. break
  785. }
  786. }
  787. }
  788. if err := validateNotNull(schema, row); err != nil {
  789. return count, err
  790. }
  791. newKey := s.table.dataKey(table, fmt.Sprintf("%v", row[schema.PrimaryKey]))
  792. if newKey != oldKey {
  793. // The primary key changed: move the staged row instead of leaving a
  794. // stale copy under the old key, and refuse to overwrite another row.
  795. if _, gerr := s.getByPKLocked(table, fmt.Sprintf("%v", row[schema.PrimaryKey])); gerr == nil {
  796. return count, fmt.Errorf("duplicate primary key: %v", row[schema.PrimaryKey])
  797. } else if gerr != ErrKeyNotFound {
  798. return count, gerr
  799. }
  800. s.stageDelete(table, oldKey, oldRow)
  801. }
  802. s.stagePut(table, newKey, row)
  803. count++
  804. }
  805. return count, nil
  806. }
  807. // Delete stages or durably applies a scan-based delete.
  808. func (s *Session) Delete(table string, filter func(Row) bool) (int, error) {
  809. s.mu.Lock()
  810. if !s.inTx {
  811. s.mu.Unlock()
  812. return s.table.Delete(table, filter)
  813. }
  814. defer s.mu.Unlock()
  815. schema, err := s.schema.GetSchema(table)
  816. if err != nil {
  817. return 0, err
  818. }
  819. rows, err := s.selectLocked(table, filter)
  820. if err != nil {
  821. return 0, err
  822. }
  823. count := 0
  824. for _, row := range rows {
  825. key := s.table.dataKey(table, fmt.Sprintf("%v", row[schema.PrimaryKey]))
  826. s.stageDelete(table, key, row)
  827. count++
  828. }
  829. return count, nil
  830. }
  831. // ClearIndex passes through to the durable table manager.
  832. func (s *Session) ClearIndex(indexName, tableName string, columns []string) error {
  833. return s.table.ClearIndex(indexName, tableName, columns)
  834. }
  835. // InvalidateCache passes through to the durable table manager.
  836. func (s *Session) InvalidateCache(table string) {
  837. s.table.InvalidateCache(table)
  838. }
  839. // BuildIndex passes through to the durable table manager.
  840. func (s *Session) BuildIndex(indexName, tableName string, columns []string) error {
  841. return s.table.BuildIndex(indexName, tableName, columns)
  842. }