tx.go 28 KB

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