tx.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  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. // A staged row was normalized against the schema as of its INSERT or UPDATE,
  159. // which a concurrent ADD COLUMN can predate. Re-apply the schema that is
  160. // current under the held gates before any derived state is computed: the CAS
  161. // check cannot reject such a row (a new key is only checked for absence), so
  162. // a NOT NULL column published after the row image was built would otherwise
  163. // be violated durably, and a UNIQUE index would not see the default the row
  164. // is about to receive. Run it before uniqueness and cache planning so both
  165. // observe the final values.
  166. if err := s.applyOverlaySchemaDefaults(); err != nil {
  167. s.resetLocked()
  168. return 0, err
  169. }
  170. // Validate scan generations for phantom detection.
  171. for t, gen := range s.scanGens {
  172. if s.table.generation(t) != gen {
  173. s.resetLocked()
  174. return 0, ErrSerialization
  175. }
  176. }
  177. for key, predicate := range s.predicateGens {
  178. if s.table.predicateGeneration(key) != predicate.gen {
  179. s.resetLocked()
  180. return 0, ErrSerialization
  181. }
  182. }
  183. // Validate the final overlay of every unique-indexed written table against
  184. // durable rows. This runs under the exclusive gate acquired above, so it
  185. // cannot race a concurrent writer. Duplicate unique values fail the commit
  186. // with a "UNIQUE constraint failed" error rather than ErrSerialization.
  187. uniquePlans := make(map[string]uniqueCachePlan, len(uniqueTables))
  188. for t := range uniqueTables {
  189. plan, err := s.table.prepareUniqueRows(t, s.overlay[t])
  190. if err != nil {
  191. s.resetLocked()
  192. return 0, err
  193. }
  194. uniquePlans[t] = plan
  195. }
  196. exclusiveTables := make(map[string]bool)
  197. for table := range uniqueTables {
  198. exclusiveTables[table] = true
  199. }
  200. for table := range s.scanGens {
  201. exclusiveTables[table] = true
  202. }
  203. for _, predicate := range s.predicateGens {
  204. exclusiveTables[predicate.table] = true
  205. }
  206. cachePlans := make(map[string]*tableCachePlan)
  207. for table, entries := range s.overlay {
  208. if exclusiveTables[table] {
  209. plan, err := s.table.prepareTableCache(table, entries, s.reads)
  210. if err != nil {
  211. s.resetLocked()
  212. return 0, err
  213. }
  214. cachePlans[table] = plan
  215. }
  216. }
  217. // Build the compare set from every observed key.
  218. checks := make([]CompareCheck, 0, len(s.reads))
  219. for key, lsn := range s.reads {
  220. checks = append(checks, CompareCheck{Key: []byte(key), LSN: lsn})
  221. }
  222. sort.Slice(checks, func(i, j int) bool { return string(checks[i].Key) < string(checks[j].Key) })
  223. // Build the batch ops from the staged overlay.
  224. ops := make([]BatchOp, 0)
  225. for _, entries := range s.overlay {
  226. for key, e := range entries {
  227. if e.absent {
  228. ops = append(ops, BatchOp{Op: batchDelete, Key: []byte(key)})
  229. } else {
  230. data, err := encodeRow(e.row)
  231. if err != nil {
  232. s.resetLocked()
  233. return 0, err
  234. }
  235. ops = append(ops, BatchOp{Op: batchPut, Key: []byte(key), Value: data})
  236. }
  237. }
  238. }
  239. sort.Slice(ops, func(i, j int) bool { return string(ops[i].Key) < string(ops[j].Key) })
  240. // A read-only transaction has nothing to write; commit trivially.
  241. if len(ops) == 0 {
  242. s.resetLocked()
  243. return 0, nil
  244. }
  245. var committed bool
  246. var commitLSN uint64
  247. err = s.table.pool.WithClient(func(c *KVClient) error {
  248. lsn, ok, err := c.CompareBatchWrite(checks, ops, nil)
  249. commitLSN = lsn
  250. committed = ok
  251. return err
  252. })
  253. if err != nil || !committed {
  254. // A transport error can hide a durable commit; a compare conflict can
  255. // also expose an out-of-band writer. Rebuild derived state next time.
  256. for table := range s.overlay {
  257. s.table.invalidateWriteFailure(table)
  258. }
  259. }
  260. if err != nil {
  261. s.resetLocked()
  262. return 0, err
  263. }
  264. if !committed {
  265. s.resetLocked()
  266. return 0, ErrSerialization
  267. }
  268. // Publish derived state before generations while retaining the table gates.
  269. for t := range s.overlay {
  270. if plan := cachePlans[t]; plan != nil {
  271. s.table.applyTableCache(plan)
  272. } else {
  273. s.table.invalidateCache(t)
  274. }
  275. s.table.applyUniquePlan(uniquePlans[t], nil)
  276. s.table.bumpIndexPredicateWildcard(t)
  277. s.table.bumpGeneration(t)
  278. }
  279. s.resetLocked()
  280. return commitLSN, nil
  281. }
  282. // acquireCommitLocks acquires the per-table gates needed to commit the staged
  283. // transaction, returning the held locks, whether each is exclusive, an unlock
  284. // function, and the set of written tables that carry a UNIQUE index. A written
  285. // table with a UNIQUE index is locked exclusively so its final overlay can be
  286. // validated against durable rows. The uniqueness probe is re-checked under the
  287. // held gates so a concurrent CREATE UNIQUE INDEX cannot slip in after the probe
  288. // and leave a duplicate unvalidated.
  289. func (s *Session) acquireCommitLocks() (locks []*sync.RWMutex, exclusive []bool, unlockAll func(), uniqueTables map[string]bool, err error) {
  290. unlock := func(ls []*sync.RWMutex, ex []bool) {
  291. for i := len(ls) - 1; i >= 0; i-- {
  292. if ex[i] {
  293. ls[i].Unlock()
  294. } else {
  295. ls[i].RUnlock()
  296. }
  297. }
  298. }
  299. for {
  300. // Tables read through scans or predicates need an exclusive validation
  301. // gate. Tables that are only written use the shared publication gate,
  302. // allowing disjoint optimistic commits to proceed concurrently while
  303. // still excluding scanner commits.
  304. affected := make(map[string]bool)
  305. for t := range s.overlay {
  306. affected[t] = false
  307. }
  308. for t := range s.scanGens {
  309. affected[t] = true
  310. }
  311. for _, predicate := range s.predicateGens {
  312. affected[predicate.table] = true
  313. }
  314. // Tables written in this transaction that carry a UNIQUE index need the
  315. // exclusive gate so their final overlay can be validated against durable
  316. // rows without racing another writer.
  317. uniqueTables = make(map[string]bool)
  318. for t := range s.overlay {
  319. uniq, err := s.table.hasUniqueIndex(t)
  320. if err != nil {
  321. return nil, nil, nil, nil, err
  322. }
  323. if uniq {
  324. uniqueTables[t] = true
  325. affected[t] = true
  326. }
  327. }
  328. tables := make([]string, 0, len(affected))
  329. for t := range affected {
  330. tables = append(tables, t)
  331. }
  332. sort.Strings(tables)
  333. locks = make([]*sync.RWMutex, len(tables))
  334. exclusive = make([]bool, len(tables))
  335. for i, t := range tables {
  336. locks[i] = s.table.tableLock(t)
  337. exclusive[i] = affected[t]
  338. }
  339. for i, lock := range locks {
  340. if exclusive[i] {
  341. lock.Lock()
  342. } else {
  343. lock.RLock()
  344. }
  345. }
  346. // Re-check under the held gates. A concurrent CREATE UNIQUE INDEX can
  347. // only have completed before we acquired the gate (it needs the exclusive
  348. // gate), so this probe is authoritative; escalate and retry if a written
  349. // table gained a unique index.
  350. retry := false
  351. for i, t := range tables {
  352. if exclusive[i] {
  353. continue
  354. }
  355. if _, written := s.overlay[t]; !written {
  356. continue
  357. }
  358. uniq, err := s.table.hasUniqueIndex(t)
  359. if err != nil {
  360. unlock(locks, exclusive)
  361. return nil, nil, nil, nil, err
  362. }
  363. if uniq {
  364. retry = true
  365. break
  366. }
  367. }
  368. if retry {
  369. unlock(locks, exclusive)
  370. continue
  371. }
  372. unlockAll = func() { unlock(locks, exclusive) }
  373. return locks, exclusive, unlockAll, uniqueTables, nil
  374. }
  375. }
  376. // applyOverlaySchemaDefaults re-applies the current schema to every staged row
  377. // (the caller holds the per-table gates). Columns published after a row image
  378. // was built receive their catalog default, and required columns are validated,
  379. // so a commit cannot persist a row that violates the schema now in effect.
  380. func (s *Session) applyOverlaySchemaDefaults() error {
  381. for table, entries := range s.overlay {
  382. schema, err := s.schema.GetSchema(table)
  383. if err != nil {
  384. return err
  385. }
  386. for _, entry := range entries {
  387. if entry.absent {
  388. continue
  389. }
  390. if err := s.schema.applySchemaDefaults(schema, entry.row); err != nil {
  391. return err
  392. }
  393. if err := s.schema.validateChecks(schema, entry.row); err != nil {
  394. return err
  395. }
  396. }
  397. }
  398. return nil
  399. }
  400. func (s *Session) resetLocked() {
  401. s.inTx = false
  402. s.aborted = false
  403. s.overlay = make(map[string]map[string]*overlayEntry)
  404. s.log = nil
  405. s.reads = make(map[string]uint64)
  406. s.scanGens = make(map[string]uint64)
  407. s.predicateGens = make(map[string]predicateRead)
  408. }
  409. func (s *Session) stagePut(table, key string, row Row) {
  410. tl := strings.ToLower(table)
  411. if s.overlay[tl] == nil {
  412. s.overlay[tl] = make(map[string]*overlayEntry)
  413. }
  414. s.log = append(s.log, txMutation{table: tl, key: key, prev: s.overlay[tl][key]})
  415. s.overlay[tl][key] = &overlayEntry{row: cloneRow(row)}
  416. if _, ok := s.reads[key]; !ok {
  417. s.reads[key] = 0
  418. }
  419. }
  420. func (s *Session) stageDelete(table, key string, row Row) {
  421. tl := strings.ToLower(table)
  422. if s.overlay[tl] == nil {
  423. s.overlay[tl] = make(map[string]*overlayEntry)
  424. }
  425. s.log = append(s.log, txMutation{table: tl, key: key, prev: s.overlay[tl][key]})
  426. // Keep the deleted row so COMMIT can exempt its rowid from the unique-index
  427. // scan and release its unique value.
  428. s.overlay[tl][key] = &overlayEntry{row: cloneRow(row), absent: true}
  429. if _, ok := s.reads[key]; !ok {
  430. s.reads[key] = 0
  431. }
  432. }
  433. // GetByPK retrieves a row by primary key, observing the staged overlay in a
  434. // transaction and recording the observed LSN for validation.
  435. func (s *Session) GetByPK(table, pk string) (Row, error) {
  436. s.mu.Lock()
  437. defer s.mu.Unlock()
  438. if !s.inTx {
  439. return s.table.GetByPK(table, pk)
  440. }
  441. key := s.table.dataKey(table, pk)
  442. tl := strings.ToLower(table)
  443. if e, ok := s.overlay[tl][key]; ok {
  444. if e.absent {
  445. return nil, ErrKeyNotFound
  446. }
  447. return cloneRow(e.row), nil
  448. }
  449. row, lsn, err := s.table.getByPKWithLSN(table, pk)
  450. if err != nil {
  451. if err == ErrKeyNotFound {
  452. s.reads[key] = 0
  453. return nil, ErrKeyNotFound
  454. }
  455. return nil, err
  456. }
  457. s.reads[key] = lsn
  458. return row, nil
  459. }
  460. // Select scans a table, merging the staged overlay so a transaction sees its
  461. // own writes, and records per-row LSNs plus the table generation.
  462. func (s *Session) Select(table string, filter func(Row) bool) ([]Row, error) {
  463. s.mu.Lock()
  464. if !s.inTx {
  465. s.mu.Unlock()
  466. return s.table.Select(table, filter)
  467. }
  468. defer s.mu.Unlock()
  469. return s.selectLocked(table, filter)
  470. }
  471. // SelectLimited bounds an autocommit scan. Explicit transactions retain the
  472. // complete overlay/read-set behavior until bounded transactional scans have a
  473. // separate phantom/overlay contract; their caller still applies LIMIT later.
  474. func (s *Session) SelectLimited(table string, filter func(Row) bool, maxRows int) ([]Row, error) {
  475. s.mu.Lock()
  476. if s.inTx {
  477. defer s.mu.Unlock()
  478. return s.selectLocked(table, filter)
  479. }
  480. s.mu.Unlock()
  481. if maxRows == 0 {
  482. return []Row{}, nil
  483. }
  484. return s.table.SelectWithLimit(table, filter, maxRows, 0)
  485. }
  486. func (s *Session) selectLocked(table string, filter func(Row) bool) ([]Row, error) {
  487. schema, err := s.schema.GetSchema(table)
  488. if err != nil {
  489. return nil, err
  490. }
  491. tl := strings.ToLower(table)
  492. tableLock := s.table.tableLock(tl)
  493. tableLock.RLock()
  494. defer tableLock.RUnlock()
  495. if _, ok := s.scanGens[tl]; !ok {
  496. s.scanGens[tl] = s.table.generation(tl)
  497. }
  498. overlay := s.overlay[tl]
  499. var rows []Row
  500. err = s.table.scanRowsWithLSN(table, func(row Row, lsn uint64) (bool, error) {
  501. pk, err := schema.PrimaryKeyForRow(row)
  502. if err != nil {
  503. return true, err
  504. }
  505. key := s.table.dataKey(table, pk)
  506. if _, ok := overlay[key]; ok {
  507. return false, nil
  508. }
  509. s.reads[key] = lsn
  510. if filter == nil || filter(row) {
  511. rows = append(rows, row)
  512. }
  513. return false, nil
  514. })
  515. if err != nil {
  516. return nil, err
  517. }
  518. for _, e := range overlay {
  519. if e.absent {
  520. continue
  521. }
  522. if filter == nil || filter(e.row) {
  523. rows = append(rows, cloneRow(e.row))
  524. }
  525. }
  526. return rows, nil
  527. }
  528. // SelectByIndex reads only matching durable rows while capturing their LSNs,
  529. // then merges the transaction overlay. The table generation protects against
  530. // matching rows being inserted or removed after the lookup.
  531. func (s *Session) SelectByIndex(table, indexName string, colValue interface{}) ([]Row, error) {
  532. s.mu.Lock()
  533. defer s.mu.Unlock()
  534. if !s.inTx {
  535. return s.table.SelectByIndex(table, indexName, colValue)
  536. }
  537. tableKey := strings.ToLower(table)
  538. index, err := s.schema.GetIndex(indexName)
  539. if err != nil {
  540. return nil, err
  541. }
  542. col := index.Columns[0].Name
  543. want := formatIndexValue(colValue)
  544. versions, predicate, err := s.table.selectByIndexWithLSN(table, indexName, colValue)
  545. if err != nil {
  546. return nil, err
  547. }
  548. if _, ok := s.predicateGens[predicate.valueKey]; !ok {
  549. s.predicateGens[predicate.valueKey] = predicateRead{table: tableKey, gen: predicate.valueGen}
  550. }
  551. if _, ok := s.predicateGens[predicate.wildcardKey]; !ok {
  552. s.predicateGens[predicate.wildcardKey] = predicateRead{table: tableKey, gen: predicate.wildcardGen}
  553. }
  554. overlay := s.overlay[tableKey]
  555. rows := make([]Row, 0, len(versions)+len(overlay))
  556. for _, version := range versions {
  557. if _, staged := overlay[version.key]; staged {
  558. continue
  559. }
  560. s.reads[version.key] = version.lsn
  561. rows = append(rows, version.row)
  562. }
  563. for _, entry := range overlay {
  564. if !entry.absent && formatIndexValue(entry.row[col]) == want {
  565. rows = append(rows, cloneRow(entry.row))
  566. }
  567. }
  568. return rows, nil
  569. }
  570. // SelectByIndexKey retrieves the rows whose index key equals valueKey, merging
  571. // the staged overlay so a transaction sees its own writes. valueKey is the
  572. // formatted key from TableManager.IndexRowKey, which supports plain, composite,
  573. // and expression indexes uniformly.
  574. func (s *Session) SelectByIndexKey(table string, idx *Index, valueKey string) ([]Row, error) {
  575. s.mu.Lock()
  576. defer s.mu.Unlock()
  577. if !s.inTx {
  578. versions, _, err := s.table.selectByIndexKeyWithLSN(table, idx.Name, valueKey)
  579. if err != nil {
  580. return nil, err
  581. }
  582. rows := make([]Row, len(versions))
  583. for i := range versions {
  584. rows[i] = versions[i].row
  585. }
  586. return rows, nil
  587. }
  588. tableKey := strings.ToLower(table)
  589. versions, predicate, err := s.table.selectByIndexKeyWithLSN(table, idx.Name, valueKey)
  590. if err != nil {
  591. return nil, err
  592. }
  593. if _, ok := s.predicateGens[predicate.valueKey]; !ok {
  594. s.predicateGens[predicate.valueKey] = predicateRead{table: tableKey, gen: predicate.valueGen}
  595. }
  596. if _, ok := s.predicateGens[predicate.wildcardKey]; !ok {
  597. s.predicateGens[predicate.wildcardKey] = predicateRead{table: tableKey, gen: predicate.wildcardGen}
  598. }
  599. overlay := s.overlay[tableKey]
  600. rows := make([]Row, 0, len(versions)+len(overlay))
  601. for _, version := range versions {
  602. if _, staged := overlay[version.key]; staged {
  603. continue
  604. }
  605. s.reads[version.key] = version.lsn
  606. rows = append(rows, version.row)
  607. }
  608. for _, entry := range overlay {
  609. if entry.absent {
  610. continue
  611. }
  612. key, kerr := s.table.IndexRowKey(idx, entry.row)
  613. if kerr != nil {
  614. return nil, kerr
  615. }
  616. if key == valueKey {
  617. rows = append(rows, cloneRow(entry.row))
  618. }
  619. }
  620. return rows, nil
  621. }
  622. // CountFast returns the exact row count, observing the staged overlay in a
  623. // transaction.
  624. func (s *Session) CountFast(table string) (int, error) {
  625. s.mu.Lock()
  626. defer s.mu.Unlock()
  627. if !s.inTx {
  628. return s.table.CountFast(table)
  629. }
  630. rows, err := s.selectLocked(table, nil)
  631. if err != nil {
  632. return 0, err
  633. }
  634. return len(rows), nil
  635. }
  636. // Insert stages an insert in a transaction, or performs a durable autocommit
  637. // insert otherwise.
  638. func (s *Session) Insert(table string, row Row) error {
  639. _, err := s.InsertWithRowID(table, row)
  640. return err
  641. }
  642. // InsertWithRowID stages an insert in a transaction, or performs a durable
  643. // autocommit insert otherwise, returning the actual generated ROWID.
  644. func (s *Session) InsertWithRowID(table string, row Row) (int64, error) {
  645. s.mu.Lock()
  646. defer s.mu.Unlock()
  647. if !s.inTx {
  648. return s.table.InsertWithRowID(table, row)
  649. }
  650. return s.insertLocked(table, row)
  651. }
  652. // InsertBulk stages or durably bulk-inserts multiple rows.
  653. func (s *Session) InsertBulk(table string, rows []Row) (int, error) {
  654. count, _, err := s.InsertBulkWithLastRowID(table, rows)
  655. return count, err
  656. }
  657. // InsertBulkWithLastRowID is InsertBulk, additionally returning the ROWID of the
  658. // last staged/persisted row (0 when nothing was inserted).
  659. func (s *Session) InsertBulkWithLastRowID(table string, rows []Row) (int, int64, error) {
  660. s.mu.Lock()
  661. defer s.mu.Unlock()
  662. if !s.inTx {
  663. return s.table.InsertBulkWithLastRowID(table, rows)
  664. }
  665. var lastRowID int64
  666. count := 0
  667. for _, row := range rows {
  668. rid, err := s.insertLocked(table, row)
  669. if err != nil {
  670. return count, lastRowID, err
  671. }
  672. lastRowID = rid
  673. count++
  674. }
  675. return count, lastRowID, nil
  676. }
  677. // insertLocked is the transaction insert helper (caller holds s.mu).
  678. func (s *Session) insertLocked(table string, row Row) (int64, error) {
  679. nr, key, err := s.table.prepareInsert(table, row)
  680. if err != nil {
  681. return 0, err
  682. }
  683. rowid, _ := rowIDFromRow(nr)
  684. tl := strings.ToLower(table)
  685. // prepareInsert returned the durable key; duplicate reporting shows the same
  686. // encoded primary-key component the key carries.
  687. pk := strings.TrimPrefix(key, s.table.dataPrefix(table))
  688. if e, ok := s.overlay[tl][key]; ok {
  689. if !e.absent {
  690. return 0, &PrimaryKeyViolationError{Table: table, Key: pk}
  691. }
  692. } else {
  693. _, lsn, err := s.table.getByPKWithLSN(table, pk)
  694. if err == nil {
  695. s.reads[key] = lsn
  696. return 0, &PrimaryKeyViolationError{Table: table, Key: pk}
  697. }
  698. if err != ErrKeyNotFound {
  699. return 0, err
  700. }
  701. s.reads[key] = 0
  702. }
  703. s.stagePut(table, key, nr)
  704. return rowid, nil
  705. }
  706. // UpdateByPK stages or durably applies a single-row update.
  707. func (s *Session) UpdateByPK(table, pk string, updateFn func(Row) (Row, error)) (Row, bool, error) {
  708. s.mu.Lock()
  709. if !s.inTx {
  710. s.mu.Unlock()
  711. return s.table.UpdateByPK(table, pk, updateFn)
  712. }
  713. defer s.mu.Unlock()
  714. schema, err := s.schema.GetSchema(table)
  715. if err != nil {
  716. return nil, false, err
  717. }
  718. key := s.table.dataKey(table, pk)
  719. row, err := s.getByPKLocked(table, pk)
  720. if err == ErrKeyNotFound {
  721. return nil, false, nil
  722. }
  723. if err != nil {
  724. return nil, false, err
  725. }
  726. oldRow := cloneRow(row)
  727. updates, err := s.runUpdateFn(updateFn, row)
  728. if err != nil {
  729. return nil, false, err
  730. }
  731. for name, value := range updates {
  732. for _, column := range schema.Columns {
  733. if strings.EqualFold(name, column.Name) {
  734. row[column.Name] = value
  735. break
  736. }
  737. }
  738. }
  739. if err := s.schema.validateRowConstraints(schema, row); err != nil {
  740. return nil, false, err
  741. }
  742. s.stagePut(table, key, row)
  743. return oldRow, true, nil
  744. }
  745. // runUpdateFn releases the session lock while invoking the update callback so the
  746. // callback can run nested reads (e.g. a scalar subquery in SET) through the same
  747. // session without deadlocking on s.mu. A connection executes one statement at a
  748. // time, so the staged overlay cannot change while the callback runs. The lock is
  749. // re-acquired before returning.
  750. func (s *Session) runUpdateFn(updateFn func(Row) (Row, error), row Row) (Row, error) {
  751. s.mu.Unlock()
  752. defer s.mu.Lock()
  753. return updateFn(row)
  754. }
  755. // DeleteByPK stages or durably applies a single-row delete.
  756. func (s *Session) DeleteByPK(table, pk string) (Row, bool, error) {
  757. s.mu.Lock()
  758. defer s.mu.Unlock()
  759. if !s.inTx {
  760. return s.table.DeleteByPK(table, pk)
  761. }
  762. key := s.table.dataKey(table, pk)
  763. row, err := s.getByPKLocked(table, pk)
  764. if err == ErrKeyNotFound {
  765. return nil, false, nil
  766. }
  767. if err != nil {
  768. return nil, false, err
  769. }
  770. s.stageDelete(table, key, row)
  771. return row, true, nil
  772. }
  773. // getByPKLocked reads a row observing the overlay (caller holds s.mu).
  774. func (s *Session) getByPKLocked(table, pk string) (Row, error) {
  775. key := s.table.dataKey(table, pk)
  776. tl := strings.ToLower(table)
  777. if e, ok := s.overlay[tl][key]; ok {
  778. if e.absent {
  779. return nil, ErrKeyNotFound
  780. }
  781. return cloneRow(e.row), nil
  782. }
  783. row, lsn, err := s.table.getByPKWithLSN(table, pk)
  784. if err != nil {
  785. if err == ErrKeyNotFound {
  786. s.reads[key] = 0
  787. return nil, ErrKeyNotFound
  788. }
  789. return nil, err
  790. }
  791. s.reads[key] = lsn
  792. return row, nil
  793. }
  794. // UpdateFunc stages or durably applies a scan-based update.
  795. func (s *Session) UpdateFunc(table string, updateFn func(Row) (Row, error), filter func(Row) bool) (int, error) {
  796. s.mu.Lock()
  797. if !s.inTx {
  798. s.mu.Unlock()
  799. return s.table.UpdateFunc(table, updateFn, filter)
  800. }
  801. defer s.mu.Unlock()
  802. schema, err := s.schema.GetSchema(table)
  803. if err != nil {
  804. return 0, err
  805. }
  806. rows, err := s.selectLocked(table, filter)
  807. if err != nil {
  808. return 0, err
  809. }
  810. count := 0
  811. for _, row := range rows {
  812. oldRow := cloneRow(row)
  813. oldPK, err := schema.PrimaryKeyForRow(row)
  814. if err != nil {
  815. return count, err
  816. }
  817. oldKey := s.table.dataKey(table, oldPK)
  818. updates, err := s.runUpdateFn(updateFn, row)
  819. if err != nil {
  820. return count, err
  821. }
  822. for name, value := range updates {
  823. for _, column := range schema.Columns {
  824. if strings.EqualFold(name, column.Name) {
  825. row[column.Name] = value
  826. break
  827. }
  828. }
  829. }
  830. if err := s.schema.validateRowConstraints(schema, row); err != nil {
  831. return count, err
  832. }
  833. newPK, err := schema.PrimaryKeyForRow(row)
  834. if err != nil {
  835. return count, err
  836. }
  837. newKey := s.table.dataKey(table, newPK)
  838. if newKey != oldKey {
  839. // The primary key changed: move the staged row instead of leaving a
  840. // stale copy under the old key, and refuse to overwrite another row.
  841. if _, gerr := s.getByPKLocked(table, newPK); gerr == nil {
  842. return count, &PrimaryKeyViolationError{Table: table, Key: newPK}
  843. } else if gerr != ErrKeyNotFound {
  844. return count, gerr
  845. }
  846. s.stageDelete(table, oldKey, oldRow)
  847. }
  848. s.stagePut(table, newKey, row)
  849. count++
  850. }
  851. return count, nil
  852. }
  853. // Delete stages or durably applies a scan-based delete.
  854. func (s *Session) Delete(table string, filter func(Row) bool) (int, error) {
  855. s.mu.Lock()
  856. if !s.inTx {
  857. s.mu.Unlock()
  858. return s.table.Delete(table, filter)
  859. }
  860. defer s.mu.Unlock()
  861. schema, err := s.schema.GetSchema(table)
  862. if err != nil {
  863. return 0, err
  864. }
  865. rows, err := s.selectLocked(table, filter)
  866. if err != nil {
  867. return 0, err
  868. }
  869. count := 0
  870. for _, row := range rows {
  871. pk, err := schema.PrimaryKeyForRow(row)
  872. if err != nil {
  873. return count, err
  874. }
  875. s.stageDelete(table, s.table.dataKey(table, pk), row)
  876. count++
  877. }
  878. return count, nil
  879. }
  880. // ClearIndex passes through to the durable table manager.
  881. func (s *Session) ClearIndex(indexName, tableName string, columns []string) error {
  882. return s.table.ClearIndex(indexName, tableName, columns)
  883. }
  884. // InvalidateCache passes through to the durable table manager.
  885. func (s *Session) InvalidateCache(table string) {
  886. s.table.InvalidateCache(table)
  887. }
  888. // BuildIndex passes through to the durable table manager.
  889. func (s *Session) BuildIndex(indexName, tableName string, columns []string) error {
  890. return s.table.BuildIndex(indexName, tableName, columns)
  891. }