tx.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  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 := applySchemaDefaults(schema, entry.row); err != nil {
  391. return err
  392. }
  393. }
  394. }
  395. return nil
  396. }
  397. func (s *Session) resetLocked() {
  398. s.inTx = false
  399. s.aborted = false
  400. s.overlay = make(map[string]map[string]*overlayEntry)
  401. s.log = nil
  402. s.reads = make(map[string]uint64)
  403. s.scanGens = make(map[string]uint64)
  404. s.predicateGens = make(map[string]predicateRead)
  405. }
  406. func (s *Session) stagePut(table, key string, row Row) {
  407. tl := strings.ToLower(table)
  408. if s.overlay[tl] == nil {
  409. s.overlay[tl] = make(map[string]*overlayEntry)
  410. }
  411. s.log = append(s.log, txMutation{table: tl, key: key, prev: s.overlay[tl][key]})
  412. s.overlay[tl][key] = &overlayEntry{row: cloneRow(row)}
  413. if _, ok := s.reads[key]; !ok {
  414. s.reads[key] = 0
  415. }
  416. }
  417. func (s *Session) stageDelete(table, key string, row Row) {
  418. tl := strings.ToLower(table)
  419. if s.overlay[tl] == nil {
  420. s.overlay[tl] = make(map[string]*overlayEntry)
  421. }
  422. s.log = append(s.log, txMutation{table: tl, key: key, prev: s.overlay[tl][key]})
  423. // Keep the deleted row so COMMIT can exempt its rowid from the unique-index
  424. // scan and release its unique value.
  425. s.overlay[tl][key] = &overlayEntry{row: cloneRow(row), absent: true}
  426. if _, ok := s.reads[key]; !ok {
  427. s.reads[key] = 0
  428. }
  429. }
  430. // GetByPK retrieves a row by primary key, observing the staged overlay in a
  431. // transaction and recording the observed LSN for validation.
  432. func (s *Session) GetByPK(table, pk string) (Row, error) {
  433. s.mu.Lock()
  434. defer s.mu.Unlock()
  435. if !s.inTx {
  436. return s.table.GetByPK(table, pk)
  437. }
  438. key := s.table.dataKey(table, pk)
  439. tl := strings.ToLower(table)
  440. if e, ok := s.overlay[tl][key]; ok {
  441. if e.absent {
  442. return nil, ErrKeyNotFound
  443. }
  444. return cloneRow(e.row), nil
  445. }
  446. row, lsn, err := s.table.getByPKWithLSN(table, pk)
  447. if err != nil {
  448. if err == ErrKeyNotFound {
  449. s.reads[key] = 0
  450. return nil, ErrKeyNotFound
  451. }
  452. return nil, err
  453. }
  454. s.reads[key] = lsn
  455. return row, nil
  456. }
  457. // Select scans a table, merging the staged overlay so a transaction sees its
  458. // own writes, and records per-row LSNs plus the table generation.
  459. func (s *Session) Select(table string, filter func(Row) bool) ([]Row, error) {
  460. s.mu.Lock()
  461. if !s.inTx {
  462. s.mu.Unlock()
  463. return s.table.Select(table, filter)
  464. }
  465. defer s.mu.Unlock()
  466. return s.selectLocked(table, filter)
  467. }
  468. // SelectLimited bounds an autocommit scan. Explicit transactions retain the
  469. // complete overlay/read-set behavior until bounded transactional scans have a
  470. // separate phantom/overlay contract; their caller still applies LIMIT later.
  471. func (s *Session) SelectLimited(table string, filter func(Row) bool, maxRows int) ([]Row, error) {
  472. s.mu.Lock()
  473. if s.inTx {
  474. defer s.mu.Unlock()
  475. return s.selectLocked(table, filter)
  476. }
  477. s.mu.Unlock()
  478. if maxRows == 0 {
  479. return []Row{}, nil
  480. }
  481. return s.table.SelectWithLimit(table, filter, maxRows, 0)
  482. }
  483. func (s *Session) selectLocked(table string, filter func(Row) bool) ([]Row, error) {
  484. schema, err := s.schema.GetSchema(table)
  485. if err != nil {
  486. return nil, err
  487. }
  488. tl := strings.ToLower(table)
  489. tableLock := s.table.tableLock(tl)
  490. tableLock.RLock()
  491. defer tableLock.RUnlock()
  492. if _, ok := s.scanGens[tl]; !ok {
  493. s.scanGens[tl] = s.table.generation(tl)
  494. }
  495. overlay := s.overlay[tl]
  496. var rows []Row
  497. err = s.table.scanRowsWithLSN(table, func(row Row, lsn uint64) (bool, error) {
  498. key := s.table.dataKey(table, fmt.Sprintf("%v", row[schema.PrimaryKey]))
  499. if _, ok := overlay[key]; ok {
  500. return false, nil
  501. }
  502. s.reads[key] = lsn
  503. if filter == nil || filter(row) {
  504. rows = append(rows, row)
  505. }
  506. return false, nil
  507. })
  508. if err != nil {
  509. return nil, err
  510. }
  511. for _, e := range overlay {
  512. if e.absent {
  513. continue
  514. }
  515. if filter == nil || filter(e.row) {
  516. rows = append(rows, cloneRow(e.row))
  517. }
  518. }
  519. return rows, nil
  520. }
  521. // SelectByIndex reads only matching durable rows while capturing their LSNs,
  522. // then merges the transaction overlay. The table generation protects against
  523. // matching rows being inserted or removed after the lookup.
  524. func (s *Session) SelectByIndex(table, indexName string, colValue interface{}) ([]Row, error) {
  525. s.mu.Lock()
  526. defer s.mu.Unlock()
  527. if !s.inTx {
  528. return s.table.SelectByIndex(table, indexName, colValue)
  529. }
  530. tableKey := strings.ToLower(table)
  531. index, err := s.schema.GetIndex(indexName)
  532. if err != nil {
  533. return nil, err
  534. }
  535. col := index.Columns[0].Name
  536. want := formatIndexValue(colValue)
  537. versions, predicate, err := s.table.selectByIndexWithLSN(table, indexName, colValue)
  538. if err != nil {
  539. return nil, err
  540. }
  541. if _, ok := s.predicateGens[predicate.valueKey]; !ok {
  542. s.predicateGens[predicate.valueKey] = predicateRead{table: tableKey, gen: predicate.valueGen}
  543. }
  544. if _, ok := s.predicateGens[predicate.wildcardKey]; !ok {
  545. s.predicateGens[predicate.wildcardKey] = predicateRead{table: tableKey, gen: predicate.wildcardGen}
  546. }
  547. overlay := s.overlay[tableKey]
  548. rows := make([]Row, 0, len(versions)+len(overlay))
  549. for _, version := range versions {
  550. if _, staged := overlay[version.key]; staged {
  551. continue
  552. }
  553. s.reads[version.key] = version.lsn
  554. rows = append(rows, version.row)
  555. }
  556. for _, entry := range overlay {
  557. if !entry.absent && formatIndexValue(entry.row[col]) == want {
  558. rows = append(rows, cloneRow(entry.row))
  559. }
  560. }
  561. return rows, nil
  562. }
  563. // SelectByIndexKey retrieves the rows whose index key equals valueKey, merging
  564. // the staged overlay so a transaction sees its own writes. valueKey is the
  565. // formatted key from TableManager.IndexRowKey, which supports plain, composite,
  566. // and expression indexes uniformly.
  567. func (s *Session) SelectByIndexKey(table string, idx *Index, valueKey string) ([]Row, error) {
  568. s.mu.Lock()
  569. defer s.mu.Unlock()
  570. if !s.inTx {
  571. versions, _, err := s.table.selectByIndexKeyWithLSN(table, idx.Name, valueKey)
  572. if err != nil {
  573. return nil, err
  574. }
  575. rows := make([]Row, len(versions))
  576. for i := range versions {
  577. rows[i] = versions[i].row
  578. }
  579. return rows, nil
  580. }
  581. tableKey := strings.ToLower(table)
  582. versions, predicate, err := s.table.selectByIndexKeyWithLSN(table, idx.Name, valueKey)
  583. if err != nil {
  584. return nil, err
  585. }
  586. if _, ok := s.predicateGens[predicate.valueKey]; !ok {
  587. s.predicateGens[predicate.valueKey] = predicateRead{table: tableKey, gen: predicate.valueGen}
  588. }
  589. if _, ok := s.predicateGens[predicate.wildcardKey]; !ok {
  590. s.predicateGens[predicate.wildcardKey] = predicateRead{table: tableKey, gen: predicate.wildcardGen}
  591. }
  592. overlay := s.overlay[tableKey]
  593. rows := make([]Row, 0, len(versions)+len(overlay))
  594. for _, version := range versions {
  595. if _, staged := overlay[version.key]; staged {
  596. continue
  597. }
  598. s.reads[version.key] = version.lsn
  599. rows = append(rows, version.row)
  600. }
  601. for _, entry := range overlay {
  602. if entry.absent {
  603. continue
  604. }
  605. key, kerr := s.table.IndexRowKey(idx, entry.row)
  606. if kerr != nil {
  607. return nil, kerr
  608. }
  609. if key == valueKey {
  610. rows = append(rows, cloneRow(entry.row))
  611. }
  612. }
  613. return rows, nil
  614. }
  615. // CountFast returns the exact row count, observing the staged overlay in a
  616. // transaction.
  617. func (s *Session) CountFast(table string) (int, error) {
  618. s.mu.Lock()
  619. defer s.mu.Unlock()
  620. if !s.inTx {
  621. return s.table.CountFast(table)
  622. }
  623. rows, err := s.selectLocked(table, nil)
  624. if err != nil {
  625. return 0, err
  626. }
  627. return len(rows), nil
  628. }
  629. // Insert stages an insert in a transaction, or performs a durable autocommit
  630. // insert otherwise.
  631. func (s *Session) Insert(table string, row Row) error {
  632. _, err := s.InsertWithRowID(table, row)
  633. return err
  634. }
  635. // InsertWithRowID stages an insert in a transaction, or performs a durable
  636. // autocommit insert otherwise, returning the actual generated ROWID.
  637. func (s *Session) InsertWithRowID(table string, row Row) (int64, error) {
  638. s.mu.Lock()
  639. defer s.mu.Unlock()
  640. if !s.inTx {
  641. return s.table.InsertWithRowID(table, row)
  642. }
  643. return s.insertLocked(table, row)
  644. }
  645. // InsertBulk stages or durably bulk-inserts multiple rows.
  646. func (s *Session) InsertBulk(table string, rows []Row) (int, error) {
  647. count, _, err := s.InsertBulkWithLastRowID(table, rows)
  648. return count, err
  649. }
  650. // InsertBulkWithLastRowID is InsertBulk, additionally returning the ROWID of the
  651. // last staged/persisted row (0 when nothing was inserted).
  652. func (s *Session) InsertBulkWithLastRowID(table string, rows []Row) (int, int64, error) {
  653. s.mu.Lock()
  654. defer s.mu.Unlock()
  655. if !s.inTx {
  656. return s.table.InsertBulkWithLastRowID(table, rows)
  657. }
  658. var lastRowID int64
  659. count := 0
  660. for _, row := range rows {
  661. rid, err := s.insertLocked(table, row)
  662. if err != nil {
  663. return count, lastRowID, err
  664. }
  665. lastRowID = rid
  666. count++
  667. }
  668. return count, lastRowID, nil
  669. }
  670. // insertLocked is the transaction insert helper (caller holds s.mu).
  671. func (s *Session) insertLocked(table string, row Row) (int64, error) {
  672. nr, key, err := s.table.prepareInsert(table, row)
  673. if err != nil {
  674. return 0, err
  675. }
  676. rowid, _ := rowIDFromRow(nr)
  677. schema, err := s.schema.GetSchema(table)
  678. if err != nil {
  679. return 0, err
  680. }
  681. pk := fmt.Sprintf("%v", nr[schema.PrimaryKey])
  682. tl := strings.ToLower(table)
  683. if e, ok := s.overlay[tl][key]; ok {
  684. if !e.absent {
  685. return 0, &PrimaryKeyViolationError{Table: table, Key: pk}
  686. }
  687. } else {
  688. _, lsn, err := s.table.getByPKWithLSN(table, pk)
  689. if err == nil {
  690. s.reads[key] = lsn
  691. return 0, &PrimaryKeyViolationError{Table: table, Key: pk}
  692. }
  693. if err != ErrKeyNotFound {
  694. return 0, err
  695. }
  696. s.reads[key] = 0
  697. }
  698. s.stagePut(table, key, nr)
  699. return rowid, nil
  700. }
  701. // UpdateByPK stages or durably applies a single-row update.
  702. func (s *Session) UpdateByPK(table, pk string, updateFn func(Row) (Row, error)) (Row, bool, error) {
  703. s.mu.Lock()
  704. if !s.inTx {
  705. s.mu.Unlock()
  706. return s.table.UpdateByPK(table, pk, updateFn)
  707. }
  708. defer s.mu.Unlock()
  709. schema, err := s.schema.GetSchema(table)
  710. if err != nil {
  711. return nil, false, err
  712. }
  713. key := s.table.dataKey(table, pk)
  714. row, err := s.getByPKLocked(table, pk)
  715. if err == ErrKeyNotFound {
  716. return nil, false, nil
  717. }
  718. if err != nil {
  719. return nil, false, err
  720. }
  721. oldRow := cloneRow(row)
  722. updates, err := s.runUpdateFn(updateFn, row)
  723. if err != nil {
  724. return nil, false, err
  725. }
  726. for name, value := range updates {
  727. for _, column := range schema.Columns {
  728. if strings.EqualFold(name, column.Name) {
  729. row[column.Name] = value
  730. break
  731. }
  732. }
  733. }
  734. if err := validateNotNull(schema, row); err != nil {
  735. return nil, false, err
  736. }
  737. s.stagePut(table, key, row)
  738. return oldRow, true, nil
  739. }
  740. // runUpdateFn releases the session lock while invoking the update callback so the
  741. // callback can run nested reads (e.g. a scalar subquery in SET) through the same
  742. // session without deadlocking on s.mu. A connection executes one statement at a
  743. // time, so the staged overlay cannot change while the callback runs. The lock is
  744. // re-acquired before returning.
  745. func (s *Session) runUpdateFn(updateFn func(Row) (Row, error), row Row) (Row, error) {
  746. s.mu.Unlock()
  747. defer s.mu.Lock()
  748. return updateFn(row)
  749. }
  750. // DeleteByPK stages or durably applies a single-row delete.
  751. func (s *Session) DeleteByPK(table, pk string) (Row, bool, error) {
  752. s.mu.Lock()
  753. defer s.mu.Unlock()
  754. if !s.inTx {
  755. return s.table.DeleteByPK(table, pk)
  756. }
  757. key := s.table.dataKey(table, pk)
  758. row, err := s.getByPKLocked(table, pk)
  759. if err == ErrKeyNotFound {
  760. return nil, false, nil
  761. }
  762. if err != nil {
  763. return nil, false, err
  764. }
  765. s.stageDelete(table, key, row)
  766. return row, true, nil
  767. }
  768. // getByPKLocked reads a row observing the overlay (caller holds s.mu).
  769. func (s *Session) getByPKLocked(table, pk string) (Row, error) {
  770. key := s.table.dataKey(table, pk)
  771. tl := strings.ToLower(table)
  772. if e, ok := s.overlay[tl][key]; ok {
  773. if e.absent {
  774. return nil, ErrKeyNotFound
  775. }
  776. return cloneRow(e.row), nil
  777. }
  778. row, lsn, err := s.table.getByPKWithLSN(table, pk)
  779. if err != nil {
  780. if err == ErrKeyNotFound {
  781. s.reads[key] = 0
  782. return nil, ErrKeyNotFound
  783. }
  784. return nil, err
  785. }
  786. s.reads[key] = lsn
  787. return row, nil
  788. }
  789. // UpdateFunc stages or durably applies a scan-based update.
  790. func (s *Session) UpdateFunc(table string, updateFn func(Row) (Row, error), filter func(Row) bool) (int, error) {
  791. s.mu.Lock()
  792. if !s.inTx {
  793. s.mu.Unlock()
  794. return s.table.UpdateFunc(table, updateFn, filter)
  795. }
  796. defer s.mu.Unlock()
  797. schema, err := s.schema.GetSchema(table)
  798. if err != nil {
  799. return 0, err
  800. }
  801. rows, err := s.selectLocked(table, filter)
  802. if err != nil {
  803. return 0, err
  804. }
  805. count := 0
  806. for _, row := range rows {
  807. oldRow := cloneRow(row)
  808. oldKey := s.table.dataKey(table, fmt.Sprintf("%v", row[schema.PrimaryKey]))
  809. updates, err := s.runUpdateFn(updateFn, row)
  810. if err != nil {
  811. return count, err
  812. }
  813. for name, value := range updates {
  814. for _, column := range schema.Columns {
  815. if strings.EqualFold(name, column.Name) {
  816. row[column.Name] = value
  817. break
  818. }
  819. }
  820. }
  821. if err := validateNotNull(schema, row); err != nil {
  822. return count, err
  823. }
  824. newKey := s.table.dataKey(table, fmt.Sprintf("%v", row[schema.PrimaryKey]))
  825. if newKey != oldKey {
  826. // The primary key changed: move the staged row instead of leaving a
  827. // stale copy under the old key, and refuse to overwrite another row.
  828. if _, gerr := s.getByPKLocked(table, fmt.Sprintf("%v", row[schema.PrimaryKey])); gerr == nil {
  829. return count, &PrimaryKeyViolationError{Table: table, Key: fmt.Sprint(row[schema.PrimaryKey])}
  830. } else if gerr != ErrKeyNotFound {
  831. return count, gerr
  832. }
  833. s.stageDelete(table, oldKey, oldRow)
  834. }
  835. s.stagePut(table, newKey, row)
  836. count++
  837. }
  838. return count, nil
  839. }
  840. // Delete stages or durably applies a scan-based delete.
  841. func (s *Session) Delete(table string, filter func(Row) bool) (int, error) {
  842. s.mu.Lock()
  843. if !s.inTx {
  844. s.mu.Unlock()
  845. return s.table.Delete(table, filter)
  846. }
  847. defer s.mu.Unlock()
  848. schema, err := s.schema.GetSchema(table)
  849. if err != nil {
  850. return 0, err
  851. }
  852. rows, err := s.selectLocked(table, filter)
  853. if err != nil {
  854. return 0, err
  855. }
  856. count := 0
  857. for _, row := range rows {
  858. key := s.table.dataKey(table, fmt.Sprintf("%v", row[schema.PrimaryKey]))
  859. s.stageDelete(table, key, row)
  860. count++
  861. }
  862. return count, nil
  863. }
  864. // ClearIndex passes through to the durable table manager.
  865. func (s *Session) ClearIndex(indexName, tableName string, columns []string) error {
  866. return s.table.ClearIndex(indexName, tableName, columns)
  867. }
  868. // InvalidateCache passes through to the durable table manager.
  869. func (s *Session) InvalidateCache(table string) {
  870. s.table.InvalidateCache(table)
  871. }
  872. // BuildIndex passes through to the durable table manager.
  873. func (s *Session) BuildIndex(indexName, tableName string, columns []string) error {
  874. return s.table.BuildIndex(indexName, tableName, columns)
  875. }