tx.go 44 KB

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