tx.go 30 KB

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