tx.go 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433
  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. // schemaTx is the transaction-scoped catalog overlay. It exists only while a
  37. // transaction is open: DDL stages into it instead of publishing, and commit
  38. // merges it into the same batch write as the staged rows. A nil overlay means
  39. // every catalog read goes straight to the shared SchemaManager.
  40. schemaTx *SchemaTx
  41. // fkCatalog caches the foreign-key metadata of the schemaTx view, keyed by
  42. // the catalog version that produced it.
  43. fkCatalog *foreignKeyCatalog
  44. fkVersion uint64
  45. }
  46. type predicateRead struct {
  47. table string
  48. gen uint64
  49. }
  50. type overlayEntry struct {
  51. row Row
  52. absent bool
  53. }
  54. type txMutation struct {
  55. table string
  56. key string
  57. prev *overlayEntry
  58. }
  59. // NewSession creates a session wrapping the given schema and table managers.
  60. func NewSession(schema *SchemaManager, table *TableManager) *Session {
  61. return &Session{
  62. schema: schema,
  63. table: table,
  64. overlay: make(map[string]map[string]*overlayEntry),
  65. reads: make(map[string]uint64),
  66. scanGens: make(map[string]uint64),
  67. predicateGens: make(map[string]predicateRead),
  68. }
  69. }
  70. // Begin starts a buffered transaction.
  71. func (s *Session) Begin() error {
  72. s.mu.Lock()
  73. defer s.mu.Unlock()
  74. if s.inTx {
  75. return fmt.Errorf("cannot start a transaction within a transaction")
  76. }
  77. s.inTx = true
  78. s.aborted = false
  79. s.overlay = make(map[string]map[string]*overlayEntry)
  80. s.log = nil
  81. s.reads = make(map[string]uint64)
  82. s.scanGens = make(map[string]uint64)
  83. s.predicateGens = make(map[string]predicateRead)
  84. s.schemaTx = newSchemaTx(s)
  85. s.fkCatalog = nil
  86. s.fkVersion = 0
  87. return nil
  88. }
  89. // InTx reports whether a transaction is in progress.
  90. func (s *Session) InTx() bool {
  91. s.mu.Lock()
  92. defer s.mu.Unlock()
  93. return s.inTx
  94. }
  95. // Abort marks the transaction as aborted without discarding state.
  96. func (s *Session) Abort() {
  97. s.mu.Lock()
  98. defer s.mu.Unlock()
  99. if s.inTx {
  100. s.aborted = true
  101. }
  102. }
  103. // Snapshot returns the current mutation-log position for a savepoint.
  104. func (s *Session) Snapshot() int {
  105. s.mu.Lock()
  106. defer s.mu.Unlock()
  107. return len(s.log)
  108. }
  109. // RollbackTo discards mutations after the given savepoint position.
  110. func (s *Session) RollbackTo(pos int) {
  111. s.mu.Lock()
  112. defer s.mu.Unlock()
  113. s.rollbackToLocked(pos)
  114. s.aborted = false
  115. }
  116. // SessionSavepoint captures the complete session state at a SQL SAVEPOINT: the
  117. // staged rows with their mutation log and read set, and the staged DDL catalog.
  118. // A rollback restores all of it, so DDL issued after a savepoint is undone with
  119. // the rows that accompanied it.
  120. type SessionSavepoint struct {
  121. datalog int
  122. overlay map[string]map[string]*overlayEntry
  123. mutationLog []txMutation
  124. reads map[string]uint64
  125. scanGens map[string]uint64
  126. predicateGens map[string]predicateRead
  127. schema *schemaTxSnapshot
  128. }
  129. // Savepoint captures the session state a later RollbackToSavepoint restores.
  130. func (s *Session) Savepoint() *SessionSavepoint {
  131. s.mu.Lock()
  132. defer s.mu.Unlock()
  133. return s.savepointLocked()
  134. }
  135. // savepointLocked captures the session state (caller holds the session lock).
  136. func (s *Session) savepointLocked() *SessionSavepoint {
  137. sp := &SessionSavepoint{
  138. datalog: len(s.log),
  139. overlay: make(map[string]map[string]*overlayEntry, len(s.overlay)),
  140. mutationLog: append([]txMutation(nil), s.log...),
  141. reads: copyLSNMap(s.reads),
  142. scanGens: copyLSNMap(s.scanGens),
  143. predicateGens: make(map[string]predicateRead, len(s.predicateGens)),
  144. }
  145. for table, entries := range s.overlay {
  146. staged := make(map[string]*overlayEntry, len(entries))
  147. for key, entry := range entries {
  148. staged[key] = entry
  149. }
  150. sp.overlay[table] = staged
  151. }
  152. for key, predicate := range s.predicateGens {
  153. sp.predicateGens[key] = predicate
  154. }
  155. if s.schemaTx != nil {
  156. snapshot := s.schemaTx.snapshot()
  157. sp.schema = &snapshot
  158. }
  159. return sp
  160. }
  161. // RollbackToSavepoint restores the state captured by Savepoint.
  162. func (s *Session) RollbackToSavepoint(sp *SessionSavepoint) {
  163. if sp == nil {
  164. return
  165. }
  166. s.mu.Lock()
  167. defer s.mu.Unlock()
  168. s.rollbackToSavepointLocked(sp)
  169. s.aborted = false
  170. }
  171. // rollbackToSavepointLocked restores a savepoint (caller holds the session
  172. // lock).
  173. func (s *Session) rollbackToSavepointLocked(sp *SessionSavepoint) {
  174. s.overlay = sp.overlay
  175. s.log = sp.mutationLog
  176. s.reads = sp.reads
  177. s.scanGens = sp.scanGens
  178. s.predicateGens = sp.predicateGens
  179. if s.schemaTx != nil && sp.schema != nil {
  180. s.schemaTx.restore(*sp.schema)
  181. }
  182. s.fkCatalog = nil
  183. s.fkVersion = 0
  184. }
  185. func copyLSNMap(source map[string]uint64) map[string]uint64 {
  186. cloned := make(map[string]uint64, len(source))
  187. for key, value := range source {
  188. cloned[key] = value
  189. }
  190. return cloned
  191. }
  192. // Rollback discards the transaction without writing anything durable.
  193. func (s *Session) Rollback() error {
  194. s.mu.Lock()
  195. defer s.mu.Unlock()
  196. if !s.inTx {
  197. return fmt.Errorf("cannot rollback: no transaction in progress")
  198. }
  199. s.resetLocked()
  200. return nil
  201. }
  202. // Commit validates and durably applies the staged transaction in one atomic
  203. // compare-and-swap batch write. It discards the commit LSN; callers that need a
  204. // ordering cursor use CommitWithLSN.
  205. func (s *Session) Commit() error {
  206. _, err := s.CommitWithLSN()
  207. return err
  208. }
  209. // CommitWithLSN behaves like Commit and additionally returns the LSN assigned
  210. // to the durable batch. A read-only or empty transaction returns zero because
  211. // no new durable state was published.
  212. func (s *Session) CommitWithLSN() (uint64, error) {
  213. s.mu.Lock()
  214. defer s.mu.Unlock()
  215. if !s.inTx {
  216. return 0, fmt.Errorf("cannot commit: no transaction in progress")
  217. }
  218. if s.aborted {
  219. s.resetLocked()
  220. return 0, fmt.Errorf("current transaction is aborted")
  221. }
  222. // Staged DDL is published by this same batch write, so the commit is atomic
  223. // across catalog changes and rows. hasDDL also forces the exclusive table
  224. // gates for the affected tables below, because the commit rewrites or
  225. // removes their durable rows.
  226. hasDDL := s.schemaTx != nil && s.schemaTx.hasDDL()
  227. // Referential integrity spans tables: a commit must validate the final
  228. // child rows against the final parent rows, including rows another table
  229. // staged in this same transaction. Take the foreign-key write gate before
  230. // any table gate (the canonical lock order) and register the constrained
  231. // component as scan reads so acquireCommitLocks holds it exclusively while
  232. // the validation scans run. A concurrent write on either side would bump one
  233. // of those generations and fail the commit with 40001 instead of committing
  234. // a dangling reference.
  235. closure, err := s.foreignKeyClosure()
  236. if err != nil {
  237. s.resetLocked()
  238. return 0, err
  239. }
  240. if len(closure) > 0 {
  241. s.table.foreignKeyMu.Lock()
  242. defer s.table.foreignKeyMu.Unlock()
  243. }
  244. for table := range closure {
  245. if _, ok := s.scanGens[table]; !ok {
  246. s.scanGens[table] = s.table.generation(table)
  247. }
  248. }
  249. // Acquire the per-table gates, escalating any table whose UNIQUE index
  250. // appeared after the initial unlocked probe. See acquireCommitLocks.
  251. _, _, unlockAll, uniqueTables, err := s.acquireCommitLocks()
  252. if err != nil {
  253. s.resetLocked()
  254. return 0, err
  255. }
  256. defer unlockAll()
  257. // Another session may have published DDL while this transaction was open.
  258. // Re-read the committed catalog under the gates so the final row validation
  259. // below sees the catalog that is actually in effect.
  260. if s.schemaTx != nil {
  261. s.schemaTx.refreshCommitted()
  262. s.fkCatalog = nil
  263. s.fkVersion = 0
  264. }
  265. // A staged row was normalized against the schema as of its INSERT or UPDATE,
  266. // which a concurrent ADD COLUMN can predate. Re-apply the schema that is
  267. // current under the held gates before any derived state is computed: the CAS
  268. // check cannot reject such a row (a new key is only checked for absence), so
  269. // a NOT NULL column published after the row image was built would otherwise
  270. // be violated durably, and a UNIQUE index would not see the default the row
  271. // is about to receive. Run it before uniqueness and cache planning so both
  272. // observe the final values.
  273. if err := s.applyOverlaySchemaDefaults(); err != nil {
  274. s.resetLocked()
  275. return 0, err
  276. }
  277. // Validate scan generations for phantom detection.
  278. for t, gen := range s.scanGens {
  279. if s.table.generation(t) != gen {
  280. s.resetLocked()
  281. return 0, ErrSerialization
  282. }
  283. }
  284. for key, predicate := range s.predicateGens {
  285. if s.table.predicateGeneration(key) != predicate.gen {
  286. s.resetLocked()
  287. return 0, ErrSerialization
  288. }
  289. }
  290. // Compute the durable effects of staged DDL before derived state is planned:
  291. // the rows an ALTER TABLE rewrites and a RENAME TABLE moves are part of the
  292. // transaction's final row state, so uniqueness and cache planning must see
  293. // them. The catalog writes travel in the same batch as everything else.
  294. var ddlOps []BatchOp
  295. var ddlChecks []CompareCheck
  296. var ddlEntries map[string]map[string]*overlayEntry
  297. var touchedTables, touchedIndexes []string
  298. if hasDDL {
  299. catalogOps, catalogChecks, err := s.schemaTx.commitCatalogOps()
  300. if err != nil {
  301. s.resetLocked()
  302. return 0, err
  303. }
  304. dataOps, dataEntries, err := s.schemaTx.commitDataOps()
  305. if err != nil {
  306. s.resetLocked()
  307. return 0, err
  308. }
  309. ddlOps = append(catalogOps, dataOps...)
  310. ddlChecks = catalogChecks
  311. ddlEntries = dataEntries
  312. touchedTables = s.schemaTx.touchedTables()
  313. touchedIndexes = s.schemaTx.touchedIndexes()
  314. }
  315. // Validate the final overlay against every foreign key in the constrained
  316. // component. The per-table gates acquired above exclude concurrent writers,
  317. // so this sees a stable state; checking the final state (rather than each
  318. // statement) is what lets a transaction delete a parent and its children in
  319. // either order as long as the committed state stays consistent.
  320. if err := s.validateForeignKeyFinalState(closure); err != nil {
  321. s.resetLocked()
  322. return 0, err
  323. }
  324. // Validate the final overlay of every unique-indexed written table against
  325. // durable rows. This runs under the exclusive gate acquired above, so it
  326. // cannot race a concurrent writer. Duplicate unique values fail the commit
  327. // with a "UNIQUE constraint failed" error rather than ErrSerialization.
  328. uniquePlans := make(map[string]uniqueCachePlan, len(uniqueTables))
  329. for t := range uniqueTables {
  330. entries := s.finalRowEntries(t, ddlEntries)
  331. plan, err := s.table.prepareUniqueRowsWith(t, entries, s.uniqueIndexesLocked(t))
  332. if err != nil {
  333. s.resetLocked()
  334. return 0, err
  335. }
  336. uniquePlans[t] = plan
  337. }
  338. exclusiveTables := make(map[string]bool)
  339. for table := range uniqueTables {
  340. exclusiveTables[table] = true
  341. }
  342. for table := range s.scanGens {
  343. exclusiveTables[table] = true
  344. }
  345. for _, predicate := range s.predicateGens {
  346. exclusiveTables[predicate.table] = true
  347. }
  348. cachePlans := make(map[string]*tableCachePlan)
  349. for table := range s.overlay {
  350. if !exclusiveTables[table] {
  351. continue
  352. }
  353. entries := s.finalRowEntries(table, ddlEntries)
  354. plan, err := s.table.prepareTableCache(table, entries, s.reads)
  355. if err != nil {
  356. s.resetLocked()
  357. return 0, err
  358. }
  359. cachePlans[table] = plan
  360. }
  361. // Build the compare set from every observed key.
  362. checks := make([]CompareCheck, 0, len(s.reads))
  363. for key, lsn := range s.reads {
  364. checks = append(checks, CompareCheck{Key: []byte(key), LSN: lsn})
  365. }
  366. // Build the batch ops from the staged overlay.
  367. ops := make([]BatchOp, 0)
  368. for _, entries := range s.overlay {
  369. for key, e := range entries {
  370. if e.absent {
  371. ops = append(ops, BatchOp{Op: batchDelete, Key: []byte(key)})
  372. } else {
  373. data, err := encodeRow(e.row)
  374. if err != nil {
  375. s.resetLocked()
  376. return 0, err
  377. }
  378. ops = append(ops, BatchOp{Op: batchPut, Key: []byte(key), Value: data})
  379. }
  380. }
  381. }
  382. if hasDDL {
  383. ops = append(ops, ddlOps...)
  384. checks = append(checks, ddlChecks...)
  385. }
  386. sort.Slice(checks, func(i, j int) bool { return string(checks[i].Key) < string(checks[j].Key) })
  387. sort.Slice(ops, func(i, j int) bool { return string(ops[i].Key) < string(ops[j].Key) })
  388. // A read-only transaction has nothing to write; commit trivially.
  389. if len(ops) == 0 {
  390. s.resetLocked()
  391. return 0, nil
  392. }
  393. var committed bool
  394. var commitLSN uint64
  395. err = s.table.pool.WithClient(func(c *KVClient) error {
  396. lsn, ok, err := c.CompareBatchWrite(checks, ops, nil)
  397. commitLSN = lsn
  398. committed = ok
  399. return err
  400. })
  401. if err != nil || !committed {
  402. // A transport error can hide a durable commit; a compare conflict can
  403. // also expose an out-of-band writer. Rebuild derived state next time.
  404. for table := range s.overlay {
  405. s.table.invalidateWriteFailure(table)
  406. }
  407. }
  408. if err != nil {
  409. s.resetLocked()
  410. return 0, err
  411. }
  412. if !committed {
  413. s.resetLocked()
  414. return 0, ErrSerialization
  415. }
  416. // Publish derived state before generations while retaining the table gates.
  417. for t := range s.overlay {
  418. if plan := cachePlans[t]; plan != nil {
  419. s.table.applyTableCache(plan)
  420. } else {
  421. s.table.invalidateCache(t)
  422. }
  423. s.table.applyUniquePlan(uniquePlans[t], nil)
  424. s.table.bumpIndexPredicateWildcard(t)
  425. s.table.bumpGeneration(t)
  426. }
  427. if hasDDL {
  428. s.publishCommittedDDL(touchedTables, touchedIndexes)
  429. }
  430. s.resetLocked()
  431. return commitLSN, nil
  432. }
  433. // publishCommittedDDL publishes a committed catalog change to the rest of the
  434. // process. The durable batch is already written, so this only drops the derived
  435. // state that described the previous catalog: the shared schema and index caches,
  436. // the row-derived caches of every touched table, and the index caches of every
  437. // touched index. Other sessions reload lazily from the committed records.
  438. func (s *Session) publishCommittedDDL(tables, indexes []string) {
  439. s.schema.invalidateCommittedDDL()
  440. for _, table := range tables {
  441. s.table.InvalidateCache(table)
  442. s.table.bumpIndexPredicateWildcard(table)
  443. s.table.bumpGeneration(table)
  444. }
  445. committed, err := s.schema.ListIndexes()
  446. if err != nil {
  447. committed = nil
  448. }
  449. known := make(map[string]bool, len(committed))
  450. for _, name := range committed {
  451. known[strings.ToLower(name)] = true
  452. }
  453. for _, index := range indexes {
  454. if !known[index] {
  455. s.table.ClearIndex(index, "", nil) //nolint:errcheck
  456. }
  457. }
  458. }
  459. // acquireCommitLocks acquires the per-table gates needed to commit the staged
  460. // transaction, returning the held locks, whether each is exclusive, an unlock
  461. // function, and the set of written tables that carry a UNIQUE index. A written
  462. // table with a UNIQUE index is locked exclusively so its final overlay can be
  463. // validated against durable rows. The uniqueness probe is re-checked under the
  464. // held gates so a concurrent CREATE UNIQUE INDEX cannot slip in after the probe
  465. // and leave a duplicate unvalidated.
  466. func (s *Session) acquireCommitLocks() (locks []*sync.RWMutex, exclusive []bool, unlockAll func(), uniqueTables map[string]bool, err error) {
  467. unlock := func(ls []*sync.RWMutex, ex []bool) {
  468. for i := len(ls) - 1; i >= 0; i-- {
  469. if ex[i] {
  470. ls[i].Unlock()
  471. } else {
  472. ls[i].RUnlock()
  473. }
  474. }
  475. }
  476. for {
  477. // Tables read through scans or predicates need an exclusive validation
  478. // gate. Tables that are only written use the shared publication gate,
  479. // allowing disjoint optimistic commits to proceed concurrently while
  480. // still excluding scanner commits.
  481. affected := make(map[string]bool)
  482. for t := range s.overlay {
  483. affected[t] = false
  484. }
  485. for t := range s.scanGens {
  486. affected[t] = true
  487. }
  488. for _, predicate := range s.predicateGens {
  489. affected[predicate.table] = true
  490. }
  491. // Staged DDL rewrites or removes durable rows and publishes catalog
  492. // records, so the commit needs the exclusive gate of every touched table.
  493. if s.schemaTx != nil && s.schemaTx.hasDDL() {
  494. for _, t := range s.schemaTx.touchedTables() {
  495. affected[t] = true
  496. }
  497. }
  498. // Tables written in this transaction that carry a UNIQUE index need the
  499. // exclusive gate so their final overlay can be validated against durable
  500. // rows without racing another writer.
  501. uniqueTables = make(map[string]bool)
  502. for t := range s.overlay {
  503. uniq, err := s.hasUniqueIndexLocked(t)
  504. if err != nil {
  505. return nil, nil, nil, nil, err
  506. }
  507. if uniq {
  508. uniqueTables[t] = true
  509. affected[t] = true
  510. }
  511. }
  512. tables := make([]string, 0, len(affected))
  513. for t := range affected {
  514. tables = append(tables, t)
  515. }
  516. sort.Strings(tables)
  517. locks = make([]*sync.RWMutex, len(tables))
  518. exclusive = make([]bool, len(tables))
  519. for i, t := range tables {
  520. locks[i] = s.table.tableLock(t)
  521. exclusive[i] = affected[t]
  522. }
  523. for i, lock := range locks {
  524. if exclusive[i] {
  525. lock.Lock()
  526. } else {
  527. lock.RLock()
  528. }
  529. }
  530. // Re-check under the held gates. A concurrent CREATE UNIQUE INDEX can
  531. // only have completed before we acquired the gate (it needs the exclusive
  532. // gate), so this probe is authoritative; escalate and retry if a written
  533. // table gained a unique index.
  534. retry := false
  535. for i, t := range tables {
  536. if exclusive[i] {
  537. continue
  538. }
  539. if _, written := s.overlay[t]; !written {
  540. continue
  541. }
  542. uniq, err := s.hasUniqueIndexLocked(t)
  543. if err != nil {
  544. unlock(locks, exclusive)
  545. return nil, nil, nil, nil, err
  546. }
  547. if uniq {
  548. retry = true
  549. break
  550. }
  551. }
  552. if retry {
  553. unlock(locks, exclusive)
  554. continue
  555. }
  556. unlockAll = func() { unlock(locks, exclusive) }
  557. return locks, exclusive, unlockAll, uniqueTables, nil
  558. }
  559. }
  560. // applyOverlaySchemaDefaults re-applies the current schema to every staged row
  561. // (the caller holds the per-table gates). Columns published after a row image
  562. // was built receive their catalog default, and required columns are validated,
  563. // so a commit cannot persist a row that violates the schema now in effect.
  564. func (s *Session) applyOverlaySchemaDefaults() error {
  565. for table, entries := range s.overlay {
  566. schema, err := s.getSchemaLocked(table)
  567. if err != nil {
  568. return err
  569. }
  570. for _, entry := range entries {
  571. if entry.absent {
  572. continue
  573. }
  574. if err := s.applyStagedRewritesLocked(table, entry.row); err != nil {
  575. return err
  576. }
  577. if err := s.schema.applySchemaDefaults(schema, entry.row); err != nil {
  578. return err
  579. }
  580. if err := s.schema.validateChecks(schema, entry.row); err != nil {
  581. return err
  582. }
  583. }
  584. }
  585. return nil
  586. }
  587. // finalRowEntries merges the rows a staged DDL rewrite or rename produces into
  588. // the table's staged entries, so uniqueness and cache planning validate the row
  589. // image the commit is about to publish (caller holds the session lock).
  590. func (s *Session) finalRowEntries(table string, ddlEntries map[string]map[string]*overlayEntry) map[string]*overlayEntry {
  591. staged := s.overlay[table]
  592. rewritten := ddlEntries[table]
  593. if len(rewritten) == 0 {
  594. return staged
  595. }
  596. merged := make(map[string]*overlayEntry, len(staged)+len(rewritten))
  597. for key, entry := range staged {
  598. merged[key] = entry
  599. }
  600. for key, entry := range rewritten {
  601. merged[key] = entry
  602. }
  603. return merged
  604. }
  605. // uniqueIndexesLocked returns the UNIQUE indexes of a table as this session
  606. // observes them (caller holds the session lock).
  607. func (s *Session) uniqueIndexesLocked(table string) []*Index {
  608. var indexes []*Index
  609. if s.schemaTx != nil {
  610. indexes, _ = s.schemaTx.listTableIndexes(table)
  611. } else {
  612. indexes, _ = s.schema.ListTableIndexes(table)
  613. }
  614. unique := indexes[:0]
  615. for _, idx := range indexes {
  616. if idx.Unique {
  617. unique = append(unique, idx)
  618. }
  619. }
  620. return unique
  621. }
  622. // hasUniqueIndexLocked reports whether the session's view of a table carries a
  623. // UNIQUE index, so a transaction validates rows against an index it staged.
  624. func (s *Session) hasUniqueIndexLocked(table string) (bool, error) {
  625. if s.schemaTx == nil {
  626. return s.table.hasUniqueIndex(table)
  627. }
  628. indexes, err := s.schemaTx.listTableIndexes(table)
  629. if err != nil {
  630. return false, err
  631. }
  632. for _, idx := range indexes {
  633. if idx.Unique {
  634. return true, nil
  635. }
  636. }
  637. return false, nil
  638. }
  639. func (s *Session) resetLocked() {
  640. s.inTx = false
  641. s.aborted = false
  642. s.overlay = make(map[string]map[string]*overlayEntry)
  643. s.log = nil
  644. s.reads = make(map[string]uint64)
  645. s.scanGens = make(map[string]uint64)
  646. s.predicateGens = make(map[string]predicateRead)
  647. s.schemaTx = nil
  648. s.fkCatalog = nil
  649. s.fkVersion = 0
  650. }
  651. func (s *Session) stagePut(table, key string, row Row) {
  652. tl := strings.ToLower(table)
  653. if s.overlay[tl] == nil {
  654. s.overlay[tl] = make(map[string]*overlayEntry)
  655. }
  656. s.log = append(s.log, txMutation{table: tl, key: key, prev: s.overlay[tl][key]})
  657. s.overlay[tl][key] = &overlayEntry{row: cloneRow(row)}
  658. if _, ok := s.reads[key]; !ok {
  659. s.reads[key] = 0
  660. }
  661. }
  662. func (s *Session) stageDelete(table, key string, row Row) {
  663. tl := strings.ToLower(table)
  664. if s.overlay[tl] == nil {
  665. s.overlay[tl] = make(map[string]*overlayEntry)
  666. }
  667. s.log = append(s.log, txMutation{table: tl, key: key, prev: s.overlay[tl][key]})
  668. // Keep the deleted row so COMMIT can exempt its rowid from the unique-index
  669. // scan and release its unique value.
  670. s.overlay[tl][key] = &overlayEntry{row: cloneRow(row), absent: true}
  671. if _, ok := s.reads[key]; !ok {
  672. s.reads[key] = 0
  673. }
  674. }
  675. // GetByPK retrieves a row by primary key, observing the staged overlay in a
  676. // transaction and recording the observed LSN for validation.
  677. func (s *Session) GetByPK(table, pk string) (Row, error) {
  678. s.mu.Lock()
  679. defer s.mu.Unlock()
  680. if !s.inTx {
  681. return s.table.GetByPK(table, pk)
  682. }
  683. stagedKey := s.table.dataKey(table, pk)
  684. tl := strings.ToLower(table)
  685. if e, ok := s.overlay[tl][stagedKey]; ok {
  686. if e.absent {
  687. return nil, ErrKeyNotFound
  688. }
  689. return cloneRow(e.row), nil
  690. }
  691. durableKey := s.durableDataKeyLocked(table, pk)
  692. row, lsn, err := s.table.getKeyWithLSN(durableKey)
  693. if err != nil {
  694. if err == ErrKeyNotFound {
  695. s.reads[durableKey] = 0
  696. return nil, ErrKeyNotFound
  697. }
  698. return nil, err
  699. }
  700. s.reads[durableKey] = lsn
  701. if err := s.applyStagedRewritesLocked(table, row); err != nil {
  702. return nil, err
  703. }
  704. return row, nil
  705. }
  706. // durableSourceLocked returns the committed table name whose data prefix holds
  707. // the rows of a table this transaction sees. RENAME TABLE moves the definition
  708. // immediately but leaves rows under the committed prefix until the commit, so
  709. // reads must follow the source (caller holds the session lock).
  710. func (s *Session) durableSourceLocked(table string) string {
  711. if s.schemaTx == nil {
  712. return table
  713. }
  714. lower := strings.ToLower(table)
  715. source, ok := s.schemaTx.dataSources[lower]
  716. if !ok || source == "" {
  717. return table
  718. }
  719. return source
  720. }
  721. // hasStagedSourceLocked reports whether the table's durable rows live under a
  722. // different (older) name because RENAME TABLE is staged.
  723. func (s *Session) hasStagedSourceLocked(table string) bool {
  724. if s.schemaTx == nil {
  725. return false
  726. }
  727. lower := strings.ToLower(table)
  728. source, ok := s.schemaTx.dataSources[lower]
  729. return ok && source != "" && source != lower
  730. }
  731. // durableDataKeyLocked returns the key a row is durably stored under, following
  732. // a staged rename (caller holds the session lock).
  733. func (s *Session) durableDataKeyLocked(table, pk string) string {
  734. return s.table.dataKey(s.durableSourceLocked(table), pk)
  735. }
  736. // Select scans a table, merging the staged overlay so a transaction sees its
  737. // own writes, and records per-row LSNs plus the table generation.
  738. func (s *Session) Select(table string, filter func(Row) bool) ([]Row, error) {
  739. s.mu.Lock()
  740. if !s.inTx {
  741. s.mu.Unlock()
  742. return s.table.Select(table, filter)
  743. }
  744. defer s.mu.Unlock()
  745. return s.selectLocked(table, filter)
  746. }
  747. // SelectLimited bounds an autocommit scan. Explicit transactions retain the
  748. // complete overlay/read-set behavior until bounded transactional scans have a
  749. // separate phantom/overlay contract; their caller still applies LIMIT later.
  750. func (s *Session) SelectLimited(table string, filter func(Row) bool, maxRows int) ([]Row, error) {
  751. s.mu.Lock()
  752. if s.inTx {
  753. defer s.mu.Unlock()
  754. return s.selectLocked(table, filter)
  755. }
  756. s.mu.Unlock()
  757. if maxRows == 0 {
  758. return []Row{}, nil
  759. }
  760. return s.table.SelectWithLimit(table, filter, maxRows, 0)
  761. }
  762. func (s *Session) selectLocked(table string, filter func(Row) bool) ([]Row, error) {
  763. schema, err := s.getSchemaLocked(table)
  764. if err != nil {
  765. return nil, err
  766. }
  767. tl := strings.ToLower(table)
  768. tableLock := s.table.tableLock(tl)
  769. tableLock.RLock()
  770. defer tableLock.RUnlock()
  771. if _, ok := s.scanGens[tl]; !ok {
  772. s.scanGens[tl] = s.table.generation(tl)
  773. }
  774. overlay := s.overlay[tl]
  775. source := s.durableSourceLocked(table)
  776. sourceLower := strings.ToLower(source)
  777. if sourceLower != tl {
  778. // A concurrent write to the committed name must invalidate the commit
  779. // just like a write to the staged name.
  780. if _, ok := s.scanGens[sourceLower]; !ok {
  781. s.scanGens[sourceLower] = s.table.generation(sourceLower)
  782. }
  783. }
  784. var rows []Row
  785. err = s.table.scanRowsAtPrefix(s.table.dataPrefix(source), func(durableKey string, row Row, lsn uint64) (bool, error) {
  786. pk, err := schema.PrimaryKeyForRow(row)
  787. if err != nil {
  788. return true, err
  789. }
  790. if _, ok := overlay[s.table.dataKey(table, pk)]; ok {
  791. return false, nil
  792. }
  793. s.reads[durableKey] = lsn
  794. if err := s.applyStagedRewritesLocked(table, row); err != nil {
  795. return true, err
  796. }
  797. if filter == nil || filter(row) {
  798. rows = append(rows, row)
  799. }
  800. return false, nil
  801. })
  802. if err != nil {
  803. return nil, err
  804. }
  805. for _, e := range overlay {
  806. if e.absent {
  807. continue
  808. }
  809. row := cloneRow(e.row)
  810. if err := s.applyStagedRewritesLocked(table, row); err != nil {
  811. return nil, err
  812. }
  813. if filter == nil || filter(row) {
  814. rows = append(rows, row)
  815. }
  816. }
  817. return rows, nil
  818. }
  819. // applyStagedRewritesLocked applies the transaction's pending ALTER TABLE row
  820. // transformations, so the session reads its own DDL before the commit writes
  821. // the transformed images (caller holds the session lock).
  822. func (s *Session) applyStagedRewritesLocked(table string, row Row) error {
  823. if s.schemaTx == nil {
  824. return nil
  825. }
  826. _, err := s.schemaTx.rewriteRow(table, row)
  827. return err
  828. }
  829. // SelectByIndex reads only matching durable rows while capturing their LSNs,
  830. // then merges the transaction overlay. The table generation protects against
  831. // matching rows being inserted or removed after the lookup.
  832. func (s *Session) SelectByIndex(table, indexName string, colValue interface{}) ([]Row, error) {
  833. s.mu.Lock()
  834. defer s.mu.Unlock()
  835. if !s.inTx {
  836. return s.table.SelectByIndex(table, indexName, colValue)
  837. }
  838. tableKey := strings.ToLower(table)
  839. index, err := s.getIndexLocked(indexName)
  840. if err != nil {
  841. return nil, err
  842. }
  843. col := index.Columns[0].Name
  844. want := formatIndexValue(colValue)
  845. if s.hasStagedSourceLocked(table) || !s.indexIsCommittedLocked(index.Name) {
  846. // The derived index caches describe the committed catalog: an index this
  847. // transaction created has no entries yet, and a renamed table's entries
  848. // are keyed under the old storage name. Either way, scan the rows the
  849. // session observes instead.
  850. return s.filterByIndexLocked(table, index, want)
  851. }
  852. versions, predicate, err := s.table.selectByIndexWithLSN(table, indexName, colValue)
  853. if err != nil {
  854. return nil, err
  855. }
  856. if _, ok := s.predicateGens[predicate.valueKey]; !ok {
  857. s.predicateGens[predicate.valueKey] = predicateRead{table: tableKey, gen: predicate.valueGen}
  858. }
  859. if _, ok := s.predicateGens[predicate.wildcardKey]; !ok {
  860. s.predicateGens[predicate.wildcardKey] = predicateRead{table: tableKey, gen: predicate.wildcardGen}
  861. }
  862. overlay := s.overlay[tableKey]
  863. rows := make([]Row, 0, len(versions)+len(overlay))
  864. for _, version := range versions {
  865. if _, staged := overlay[version.key]; staged {
  866. continue
  867. }
  868. s.reads[version.key] = version.lsn
  869. if err := s.applyStagedRewritesLocked(table, version.row); err != nil {
  870. return nil, err
  871. }
  872. rows = append(rows, version.row)
  873. }
  874. for _, entry := range overlay {
  875. if !entry.absent && formatIndexValue(entry.row[col]) == want {
  876. rows = append(rows, cloneRow(entry.row))
  877. }
  878. }
  879. return rows, nil
  880. }
  881. // SelectByIndexKey retrieves the rows whose index key equals valueKey, merging
  882. // the staged overlay so a transaction sees its own writes. valueKey is the
  883. // formatted key from TableManager.IndexRowKey, which supports plain, composite,
  884. // and expression indexes uniformly.
  885. func (s *Session) SelectByIndexKey(table string, idx *Index, valueKey string) ([]Row, error) {
  886. s.mu.Lock()
  887. defer s.mu.Unlock()
  888. if !s.inTx {
  889. versions, _, err := s.table.selectByIndexKeyWithLSN(table, idx.Name, valueKey)
  890. if err != nil {
  891. return nil, err
  892. }
  893. rows := make([]Row, len(versions))
  894. for i := range versions {
  895. rows[i] = versions[i].row
  896. }
  897. return rows, nil
  898. }
  899. tableKey := strings.ToLower(table)
  900. if s.hasStagedSourceLocked(table) || !s.indexIsCommittedLocked(idx.Name) {
  901. return s.filterByIndexLocked(table, idx, valueKey)
  902. }
  903. versions, predicate, err := s.table.selectByIndexKeyWithLSN(table, idx.Name, valueKey)
  904. if err != nil {
  905. return nil, err
  906. }
  907. if _, ok := s.predicateGens[predicate.valueKey]; !ok {
  908. s.predicateGens[predicate.valueKey] = predicateRead{table: tableKey, gen: predicate.valueGen}
  909. }
  910. if _, ok := s.predicateGens[predicate.wildcardKey]; !ok {
  911. s.predicateGens[predicate.wildcardKey] = predicateRead{table: tableKey, gen: predicate.wildcardGen}
  912. }
  913. overlay := s.overlay[tableKey]
  914. rows := make([]Row, 0, len(versions)+len(overlay))
  915. for _, version := range versions {
  916. if _, staged := overlay[version.key]; staged {
  917. continue
  918. }
  919. s.reads[version.key] = version.lsn
  920. if err := s.applyStagedRewritesLocked(table, version.row); err != nil {
  921. return nil, err
  922. }
  923. rows = append(rows, version.row)
  924. }
  925. for _, entry := range overlay {
  926. if entry.absent {
  927. continue
  928. }
  929. key, kerr := s.table.IndexRowKey(idx, entry.row)
  930. if kerr != nil {
  931. return nil, kerr
  932. }
  933. if key == valueKey {
  934. rows = append(rows, cloneRow(entry.row))
  935. }
  936. }
  937. return rows, nil
  938. }
  939. // filterByIndexLocked returns the rows this session observes whose index key
  940. // equals valueKey, without consulting the derived index caches. It is the
  941. // fallback for a table renamed in this transaction, whose committed index
  942. // entries still name the old storage prefix (caller holds the session lock).
  943. func (s *Session) filterByIndexLocked(table string, idx *Index, valueKey string) ([]Row, error) {
  944. rows, err := s.selectLocked(table, nil)
  945. if err != nil {
  946. return nil, err
  947. }
  948. matched := make([]Row, 0, len(rows))
  949. for _, row := range rows {
  950. key, err := s.table.IndexRowKey(idx, row)
  951. if err != nil {
  952. return nil, err
  953. }
  954. if key == valueKey {
  955. matched = append(matched, row)
  956. }
  957. }
  958. return matched, nil
  959. }
  960. // indexIsCommittedLocked reports whether the shared table manager can resolve an
  961. // index, and therefore whether its derived index caches cover it (caller holds
  962. // the session lock).
  963. func (s *Session) indexIsCommittedLocked(name string) bool {
  964. _, err := s.schema.GetIndex(name)
  965. return err == nil
  966. }
  967. // getIndexLocked resolves an index definition against the session catalog
  968. // (caller holds the session lock).
  969. func (s *Session) getIndexLocked(name string) (*Index, error) {
  970. if s.schemaTx != nil {
  971. return s.schemaTx.getIndex(name)
  972. }
  973. return s.schema.GetIndex(name)
  974. }
  975. // CountFast returns the exact row count, observing the staged overlay in a
  976. // transaction.
  977. func (s *Session) CountFast(table string) (int, error) {
  978. s.mu.Lock()
  979. defer s.mu.Unlock()
  980. if !s.inTx {
  981. return s.table.CountFast(table)
  982. }
  983. rows, err := s.selectLocked(table, nil)
  984. if err != nil {
  985. return 0, err
  986. }
  987. return len(rows), nil
  988. }
  989. // Insert stages an insert in a transaction, or performs a durable autocommit
  990. // insert otherwise.
  991. func (s *Session) Insert(table string, row Row) error {
  992. _, err := s.InsertWithRowID(table, row)
  993. return err
  994. }
  995. // InsertWithRowID stages an insert in a transaction, or performs a durable
  996. // autocommit insert otherwise, returning the actual generated ROWID.
  997. func (s *Session) InsertWithRowID(table string, row Row) (int64, error) {
  998. s.mu.Lock()
  999. defer s.mu.Unlock()
  1000. if !s.inTx {
  1001. return s.table.InsertWithRowID(table, row)
  1002. }
  1003. return s.insertLocked(table, row)
  1004. }
  1005. // InsertBulk stages or durably bulk-inserts multiple rows.
  1006. func (s *Session) InsertBulk(table string, rows []Row) (int, error) {
  1007. count, _, err := s.InsertBulkWithLastRowID(table, rows)
  1008. return count, err
  1009. }
  1010. // InsertBulkWithLastRowID is InsertBulk, additionally returning the ROWID of the
  1011. // last staged/persisted row (0 when nothing was inserted).
  1012. func (s *Session) InsertBulkWithLastRowID(table string, rows []Row) (int, int64, error) {
  1013. s.mu.Lock()
  1014. defer s.mu.Unlock()
  1015. if !s.inTx {
  1016. return s.table.InsertBulkWithLastRowID(table, rows)
  1017. }
  1018. var lastRowID int64
  1019. count := 0
  1020. for _, row := range rows {
  1021. rid, err := s.insertLocked(table, row)
  1022. if err != nil {
  1023. return count, lastRowID, err
  1024. }
  1025. lastRowID = rid
  1026. count++
  1027. }
  1028. return count, lastRowID, nil
  1029. }
  1030. // insertLocked is the transaction insert helper (caller holds s.mu).
  1031. func (s *Session) insertLocked(table string, row Row) (int64, error) {
  1032. schema, err := s.getSchemaLocked(table)
  1033. if err != nil {
  1034. return 0, err
  1035. }
  1036. nr, key, err := s.table.prepareInsertWithSchema(table, schema, row)
  1037. if err != nil {
  1038. return 0, err
  1039. }
  1040. rowid, _ := rowIDFromRow(nr)
  1041. tl := strings.ToLower(table)
  1042. // prepareInsert returned the durable key; duplicate reporting shows the same
  1043. // encoded primary-key component the key carries.
  1044. pk := strings.TrimPrefix(key, s.table.dataPrefix(table))
  1045. if e, ok := s.overlay[tl][key]; ok {
  1046. if !e.absent {
  1047. return 0, &PrimaryKeyViolationError{Table: table, Key: pk}
  1048. }
  1049. } else {
  1050. durableKey := s.durableDataKeyLocked(table, pk)
  1051. _, lsn, err := s.table.getKeyWithLSN(durableKey)
  1052. if err == nil {
  1053. s.reads[durableKey] = lsn
  1054. return 0, &PrimaryKeyViolationError{Table: table, Key: pk}
  1055. }
  1056. if err != nil && err != ErrKeyNotFound {
  1057. return 0, err
  1058. }
  1059. s.reads[durableKey] = 0
  1060. }
  1061. s.stagePut(table, key, nr)
  1062. return rowid, nil
  1063. }
  1064. // UpdateByPK stages or durably applies a single-row update. A table that is the
  1065. // parent of a cascading constraint runs in an implicit transaction so the parent
  1066. // rewrite and every cascaded row publish in one commit.
  1067. func (s *Session) UpdateByPK(table, pk string, updateFn func(Row) (Row, error)) (Row, bool, error) {
  1068. s.mu.Lock()
  1069. if !s.inTx {
  1070. s.mu.Unlock()
  1071. cascading, unlockFK, err := s.beginCascadingPointWrite(table, false)
  1072. if err != nil {
  1073. return nil, false, err
  1074. }
  1075. if !cascading {
  1076. return s.table.UpdateByPK(table, pk, updateFn)
  1077. }
  1078. oldRow, updated, err := s.updateByPKStaged(table, pk, updateFn)
  1079. unlockFK()
  1080. if err != nil {
  1081. _ = s.Rollback()
  1082. return nil, false, err
  1083. }
  1084. if err := s.Commit(); err != nil {
  1085. return nil, false, err
  1086. }
  1087. return oldRow, updated, nil
  1088. }
  1089. defer s.mu.Unlock()
  1090. return s.updateByPKLocked(table, pk, updateFn)
  1091. }
  1092. func (s *Session) updateByPKStaged(table, pk string, updateFn func(Row) (Row, error)) (Row, bool, error) {
  1093. s.mu.Lock()
  1094. defer s.mu.Unlock()
  1095. return s.updateByPKLocked(table, pk, updateFn)
  1096. }
  1097. // updateByPKLocked stages a point update. The caller holds the session lock and
  1098. // a transaction.
  1099. func (s *Session) updateByPKLocked(table, pk string, updateFn func(Row) (Row, error)) (Row, bool, error) {
  1100. schema, err := s.getSchemaLocked(table)
  1101. if err != nil {
  1102. return nil, false, err
  1103. }
  1104. row, err := s.getByPKLocked(table, pk)
  1105. if err == ErrKeyNotFound {
  1106. return nil, false, nil
  1107. }
  1108. if err != nil {
  1109. return nil, false, err
  1110. }
  1111. oldRow := cloneRow(row)
  1112. updates, err := s.runUpdateFn(updateFn, row)
  1113. if err != nil {
  1114. return nil, false, err
  1115. }
  1116. for name, value := range updates {
  1117. for _, column := range schema.Columns {
  1118. if strings.EqualFold(name, column.Name) {
  1119. row[column.Name] = value
  1120. break
  1121. }
  1122. }
  1123. }
  1124. if err := s.schema.validateRowConstraints(schema, row); err != nil {
  1125. return nil, false, err
  1126. }
  1127. pos := len(s.log)
  1128. if err := s.stageCascadeUpdate(table, oldRow, row, newCascadeExpansion(s.schema)); err != nil {
  1129. s.rollbackToLocked(pos)
  1130. return nil, false, err
  1131. }
  1132. return oldRow, true, nil
  1133. }
  1134. // runUpdateFn releases the session lock while invoking the update callback so the
  1135. // callback can run nested reads (e.g. a scalar subquery in SET) through the same
  1136. // session without deadlocking on s.mu. A connection executes one statement at a
  1137. // time, so the staged overlay cannot change while the callback runs. The lock is
  1138. // re-acquired before returning.
  1139. func (s *Session) runUpdateFn(updateFn func(Row) (Row, error), row Row) (Row, error) {
  1140. s.mu.Unlock()
  1141. defer s.mu.Lock()
  1142. return updateFn(row)
  1143. }
  1144. // DeleteByPK stages or durably applies a single-row delete. A table that is the
  1145. // parent of a cascading constraint runs in an implicit transaction so the
  1146. // parent delete and every cascaded row publish in one commit.
  1147. func (s *Session) DeleteByPK(table, pk string) (Row, bool, error) {
  1148. s.mu.Lock()
  1149. if !s.inTx {
  1150. s.mu.Unlock()
  1151. cascading, unlockFK, err := s.beginCascadingPointWrite(table, true)
  1152. if err != nil {
  1153. return nil, false, err
  1154. }
  1155. if !cascading {
  1156. return s.table.DeleteByPK(table, pk)
  1157. }
  1158. row, deleted, err := s.deleteByPKStaged(table, pk)
  1159. unlockFK()
  1160. if err != nil {
  1161. _ = s.Rollback()
  1162. return nil, false, err
  1163. }
  1164. if err := s.Commit(); err != nil {
  1165. return nil, false, err
  1166. }
  1167. return row, deleted, nil
  1168. }
  1169. defer s.mu.Unlock()
  1170. return s.deleteByPKLocked(table, pk)
  1171. }
  1172. func (s *Session) deleteByPKStaged(table, pk string) (Row, bool, error) {
  1173. s.mu.Lock()
  1174. defer s.mu.Unlock()
  1175. return s.deleteByPKLocked(table, pk)
  1176. }
  1177. // deleteByPKLocked stages a point delete. The caller holds the session lock and
  1178. // a transaction.
  1179. func (s *Session) deleteByPKLocked(table, pk string) (Row, bool, error) {
  1180. key := s.table.dataKey(table, pk)
  1181. row, err := s.getByPKLocked(table, pk)
  1182. if err == ErrKeyNotFound {
  1183. return nil, false, nil
  1184. }
  1185. if err != nil {
  1186. return nil, false, err
  1187. }
  1188. pos := len(s.log)
  1189. if err := s.stageCascadeDelete(table, key, row, newCascadeExpansion(s.schema)); err != nil {
  1190. s.rollbackToLocked(pos)
  1191. return nil, false, err
  1192. }
  1193. return row, true, nil
  1194. }
  1195. // getByPKLocked reads a row observing the overlay (caller holds s.mu).
  1196. func (s *Session) getByPKLocked(table, pk string) (Row, error) {
  1197. key := s.table.dataKey(table, pk)
  1198. tl := strings.ToLower(table)
  1199. if e, ok := s.overlay[tl][key]; ok {
  1200. if e.absent {
  1201. return nil, ErrKeyNotFound
  1202. }
  1203. return cloneRow(e.row), nil
  1204. }
  1205. row, lsn, err := s.table.getByPKWithLSN(table, pk)
  1206. if err != nil {
  1207. if err == ErrKeyNotFound {
  1208. s.reads[key] = 0
  1209. return nil, ErrKeyNotFound
  1210. }
  1211. return nil, err
  1212. }
  1213. s.reads[key] = lsn
  1214. if err := s.applyStagedRewritesLocked(table, row); err != nil {
  1215. return nil, err
  1216. }
  1217. return row, nil
  1218. }
  1219. // UpdateFunc stages or durably applies a scan-based update.
  1220. func (s *Session) UpdateFunc(table string, updateFn func(Row) (Row, error), filter func(Row) bool) (int, error) {
  1221. s.mu.Lock()
  1222. if !s.inTx {
  1223. s.mu.Unlock()
  1224. return s.table.UpdateFunc(table, updateFn, filter)
  1225. }
  1226. defer s.mu.Unlock()
  1227. schema, err := s.getSchemaLocked(table)
  1228. if err != nil {
  1229. return 0, err
  1230. }
  1231. rows, err := s.selectLocked(table, filter)
  1232. if err != nil {
  1233. return 0, err
  1234. }
  1235. count := 0
  1236. exp := newCascadeExpansion(s.schema)
  1237. pos := len(s.log)
  1238. for _, row := range rows {
  1239. oldRow := cloneRow(row)
  1240. updates, err := s.runUpdateFn(updateFn, row)
  1241. if err != nil {
  1242. s.rollbackToLocked(pos)
  1243. return count, err
  1244. }
  1245. for name, value := range updates {
  1246. for _, column := range schema.Columns {
  1247. if strings.EqualFold(name, column.Name) {
  1248. row[column.Name] = value
  1249. break
  1250. }
  1251. }
  1252. }
  1253. if err := s.schema.validateRowConstraints(schema, row); err != nil {
  1254. s.rollbackToLocked(pos)
  1255. return count, err
  1256. }
  1257. if err := s.stageCascadeUpdate(table, oldRow, row, exp); err != nil {
  1258. s.rollbackToLocked(pos)
  1259. return count, err
  1260. }
  1261. count++
  1262. }
  1263. return count, nil
  1264. }
  1265. // Delete stages or durably applies a scan-based delete.
  1266. func (s *Session) Delete(table string, filter func(Row) bool) (int, error) {
  1267. s.mu.Lock()
  1268. if !s.inTx {
  1269. s.mu.Unlock()
  1270. return s.table.Delete(table, filter)
  1271. }
  1272. defer s.mu.Unlock()
  1273. schema, err := s.getSchemaLocked(table)
  1274. if err != nil {
  1275. return 0, err
  1276. }
  1277. rows, err := s.selectLocked(table, filter)
  1278. if err != nil {
  1279. return 0, err
  1280. }
  1281. count := 0
  1282. exp := newCascadeExpansion(s.schema)
  1283. pos := len(s.log)
  1284. for _, row := range rows {
  1285. pk, err := schema.PrimaryKeyForRow(row)
  1286. if err != nil {
  1287. s.rollbackToLocked(pos)
  1288. return count, err
  1289. }
  1290. if err := s.stageCascadeDelete(table, s.table.dataKey(table, pk), row, exp); err != nil {
  1291. s.rollbackToLocked(pos)
  1292. return count, err
  1293. }
  1294. count++
  1295. }
  1296. return count, nil
  1297. }
  1298. // ClearIndex drops the in-memory entries of an index. Inside a transaction the
  1299. // drop is staged in the catalog overlay instead: the committed index (and its
  1300. // cache) stays intact for every other session, and the commit clears it once the
  1301. // catalog change is durable.
  1302. func (s *Session) ClearIndex(indexName, tableName string, columns []string) error {
  1303. s.mu.Lock()
  1304. defer s.mu.Unlock()
  1305. if s.schemaTx != nil && s.schemaTx.hasDDL() {
  1306. return nil
  1307. }
  1308. return s.table.ClearIndex(indexName, tableName, columns)
  1309. }
  1310. // InvalidateCache drops the derived caches of a table. Inside a transaction the
  1311. // durable rows are still current, so nothing is invalidated until the commit
  1312. // publishes the catalog change.
  1313. func (s *Session) InvalidateCache(table string) {
  1314. s.mu.Lock()
  1315. defer s.mu.Unlock()
  1316. if s.schemaTx != nil {
  1317. return
  1318. }
  1319. s.table.InvalidateCache(table)
  1320. }
  1321. // BuildIndex builds index entries for every existing row. Inside a transaction
  1322. // the index is only staged; its entries are derived lazily from durable rows
  1323. // once the commit publishes it and the session is merged in afterwards.
  1324. func (s *Session) BuildIndex(indexName, tableName string, columns []string) error {
  1325. s.mu.Lock()
  1326. defer s.mu.Unlock()
  1327. if s.schemaTx != nil {
  1328. return nil
  1329. }
  1330. return s.table.BuildIndex(indexName, tableName, columns)
  1331. }