table.go 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050
  1. package storage
  2. import (
  3. "errors"
  4. "fmt"
  5. "hash/fnv"
  6. "math"
  7. "strconv"
  8. "strings"
  9. "sync"
  10. "time"
  11. )
  12. // Row represents a database row.
  13. type Row map[string]interface{}
  14. // UniqueViolationError reports a duplicate value on a UNIQUE index. The
  15. // constraint name identifies the violated index so protocol layers can surface a
  16. // machine-detectable error.
  17. type UniqueViolationError struct {
  18. Constraint string
  19. }
  20. func (e *UniqueViolationError) Error() string {
  21. return fmt.Sprintf("UNIQUE constraint failed: %s", e.Constraint)
  22. }
  23. // TableManager manages table data operations.
  24. type TableManager struct {
  25. pool *KVPool
  26. schema *SchemaManager
  27. database string
  28. cacheMu sync.RWMutex
  29. uniqueCache map[string]*uniqueIndexCache
  30. indexRowValues map[string]map[int64]string // index name → rowid → candidate key
  31. keyRowCache map[string]map[string]int64 // table name → primary key → rowid
  32. indexCache map[string]map[string][]int64 // index name → indexed value → rowids
  33. indexTable map[string]string // index name → table name
  34. rowKeyCache map[string]map[int64]string // table name → rowid → primary key
  35. // disabledIndexes prevents a concurrent lookup from rebuilding an index
  36. // after DROP has cleared it but before the schema entry is removed.
  37. disabledIndexes map[string]bool
  38. // counts holds exact per-table row counts for the COUNT(*) fast path.
  39. // It is derived lazily from durable rows on first use and maintained
  40. // incrementally by Insert/InsertBulk/Delete thereafter.
  41. counts map[string]int
  42. countsInit map[string]bool
  43. countGeneration map[string]time.Time
  44. // stripes are deterministic per-key locks used by point operations
  45. // (GetByPK/Insert/UpdateByPK/DeleteByPK). They replace the table-wide lock
  46. // so point operations on different keys of the same table proceed
  47. // concurrently. Index is derived from the full data key (database+table+pk).
  48. stripes [64]sync.Mutex
  49. // foreignKeyMu serializes writes that touch a table participating in a
  50. // FOREIGN KEY, so a child-side or parent-side validation scan cannot
  51. // interleave with a conflicting write. It is always acquired before any
  52. // table gate.
  53. foreignKeyMu sync.Mutex
  54. // generations tracks full-table scans. predicateGenerations narrows indexed
  55. // equality reads to one index value so unrelated writes do not conflict.
  56. genMu sync.Mutex
  57. generations map[string]uint64
  58. predicateGenerations map[string]uint64
  59. // exprMu guards exprEval, the pluggable evaluator for expression-index
  60. // columns. It is set by the SQL executor so storage stays independent of
  61. // the SQL front end.
  62. exprMu sync.RWMutex
  63. exprEval ExpressionEvaluator
  64. }
  65. // ExpressionEvaluator computes the value of a persisted index expression for a
  66. // row. The SQL executor registers one so the storage layer can enforce
  67. // expression indexes without importing the parser/executor.
  68. type ExpressionEvaluator func(expression string, row Row) (interface{}, error)
  69. // SetExpressionEvaluator installs the evaluator used to compute expression-index
  70. // values during uniqueness validation and index maintenance.
  71. func (m *TableManager) SetExpressionEvaluator(eval ExpressionEvaluator) {
  72. m.exprMu.Lock()
  73. m.exprEval = eval
  74. m.exprMu.Unlock()
  75. }
  76. func (m *TableManager) expressionEvaluator() ExpressionEvaluator {
  77. m.exprMu.RLock()
  78. defer m.exprMu.RUnlock()
  79. return m.exprEval
  80. }
  81. // NewTableManager creates a new table manager.
  82. func NewTableManager(pool *KVPool, schema *SchemaManager, database string) *TableManager {
  83. return &TableManager{
  84. pool: pool,
  85. schema: schema,
  86. database: database,
  87. uniqueCache: make(map[string]*uniqueIndexCache),
  88. indexRowValues: make(map[string]map[int64]string),
  89. keyRowCache: make(map[string]map[string]int64),
  90. indexCache: make(map[string]map[string][]int64),
  91. indexTable: make(map[string]string),
  92. rowKeyCache: make(map[string]map[int64]string),
  93. disabledIndexes: make(map[string]bool),
  94. counts: make(map[string]int),
  95. countsInit: make(map[string]bool),
  96. countGeneration: make(map[string]time.Time),
  97. generations: make(map[string]uint64),
  98. predicateGenerations: make(map[string]uint64),
  99. }
  100. }
  101. func (m *TableManager) tableLock(key string) *sync.RWMutex {
  102. return m.schema.tableLock(key)
  103. }
  104. // stripeKey returns the deterministic striped lock for a point operation on the
  105. // given full data key. Point operations on different keys therefore serialize
  106. // independently, while operations on the same key are mutually exclusive.
  107. func (m *TableManager) stripeKey(key string) *sync.Mutex {
  108. h := fnv.New32a()
  109. h.Write([]byte(key))
  110. return &m.stripes[h.Sum32()%uint32(len(m.stripes))]
  111. }
  112. // generation returns the current in-process generation for a table. It is
  113. // bumped on every committed write and captured by transaction scans.
  114. func (m *TableManager) generation(table string) uint64 {
  115. key := strings.ToLower(table)
  116. m.genMu.Lock()
  117. g := m.generations[key]
  118. m.genMu.Unlock()
  119. return g
  120. }
  121. // bumpGeneration advances a table's generation. Callers hold the table gate in
  122. // shared mode for point writes or exclusive mode for scan-based writes.
  123. func (m *TableManager) bumpGeneration(table string) {
  124. key := strings.ToLower(table)
  125. m.genMu.Lock()
  126. m.generations[key]++
  127. m.genMu.Unlock()
  128. }
  129. func indexPredicateKey(table, indexName, value string) string {
  130. return strings.ToLower(table) + "\x00" + strings.ToLower(indexName) + "\x00" + value
  131. }
  132. func indexPredicateWildcardKey(table string) string {
  133. return strings.ToLower(table) + "\x00*"
  134. }
  135. func (m *TableManager) predicateSnapshot(table, indexName, value string) (string, uint64, string, uint64) {
  136. valueKey := indexPredicateKey(table, indexName, value)
  137. wildcardKey := indexPredicateWildcardKey(table)
  138. m.genMu.Lock()
  139. valueGen := m.predicateGenerations[valueKey]
  140. wildcardGen := m.predicateGenerations[wildcardKey]
  141. m.genMu.Unlock()
  142. return valueKey, valueGen, wildcardKey, wildcardGen
  143. }
  144. func (m *TableManager) predicateGeneration(key string) uint64 {
  145. m.genMu.Lock()
  146. gen := m.predicateGenerations[key]
  147. m.genMu.Unlock()
  148. return gen
  149. }
  150. func (m *TableManager) bumpIndexPredicates(table string, rows ...Row) error {
  151. indexes, err := m.schema.ListTableIndexes(table)
  152. if err != nil || len(indexes) == 0 {
  153. return err
  154. }
  155. m.genMu.Lock()
  156. defer m.genMu.Unlock()
  157. for _, row := range rows {
  158. if row == nil {
  159. continue
  160. }
  161. for _, index := range indexes {
  162. value, err := m.buildIndexValue(row, index.Columns)
  163. if err != nil {
  164. return err
  165. }
  166. m.predicateGenerations[indexPredicateKey(table, index.Name, value)]++
  167. }
  168. }
  169. return nil
  170. }
  171. func (m *TableManager) bumpIndexPredicateWildcard(table string) {
  172. m.genMu.Lock()
  173. m.predicateGenerations[indexPredicateWildcardKey(table)]++
  174. m.genMu.Unlock()
  175. }
  176. // compareWritePoint issues a single CompareBatchWrite against the pooled KV.
  177. // It returns whether the compare checks held and the ops committed.
  178. func (m *TableManager) compareWritePoint(checks []CompareCheck, ops []BatchOp) (bool, error) {
  179. var committed bool
  180. err := m.pool.WithClient(func(c *KVClient) error {
  181. _, ok, err := c.CompareBatchWrite(checks, ops, nil)
  182. committed = ok
  183. return err
  184. })
  185. return committed, err
  186. }
  187. // invalidateCache removes a table's derived in-memory indexes.
  188. func (m *TableManager) invalidateCache(table string) {
  189. m.cacheMu.Lock()
  190. key := strings.ToLower(table)
  191. delete(m.rowKeyCache, key)
  192. delete(m.keyRowCache, key)
  193. delete(m.counts, key)
  194. delete(m.countsInit, key)
  195. delete(m.countGeneration, key)
  196. for indexName, tableName := range m.indexTable {
  197. if tableName == key {
  198. delete(m.indexCache, indexName)
  199. delete(m.indexRowValues, indexName)
  200. delete(m.indexTable, indexName)
  201. }
  202. }
  203. m.cacheMu.Unlock()
  204. }
  205. // InvalidateCache is the exported version for use by the executor.
  206. func (m *TableManager) InvalidateCache(table string) {
  207. m.invalidateCache(table)
  208. m.cacheMu.Lock()
  209. for name, cache := range m.uniqueCache {
  210. if cache.table == strings.ToLower(table) {
  211. delete(m.uniqueCache, name)
  212. }
  213. }
  214. m.cacheMu.Unlock()
  215. }
  216. // rowVisitFunc is invoked for each decoded row in a streaming scan. Return
  217. // stop=true to end the scan early; a non-nil error aborts the scan.
  218. type rowVisitFunc func(Row) (stop bool, err error)
  219. // scanRows streams the rows of table by scanning durable KV rows one page at a
  220. // time under a single pooled client. Each page is decoded as it arrives and
  221. // passed to fn, which may stop the scan early. The cursor is always closed and
  222. // the client always returned to the pool, even on error.
  223. func (m *TableManager) scanRows(table string, fn rowVisitFunc) error {
  224. return m.scanRowsWithPageSize(table, scanPageSize, fn)
  225. }
  226. func (m *TableManager) scanRowsWithPageSize(table string, pageSize uint32, fn rowVisitFunc) error {
  227. return m.pool.WithClient(func(client *KVClient) (retErr error) {
  228. cursor, err := client.ScanWithLimit([]byte(m.dataPrefix(table)), pageSize)
  229. if err != nil {
  230. return err
  231. }
  232. defer func() {
  233. if err := cursor.Close(); retErr == nil {
  234. retErr = err
  235. }
  236. }()
  237. for {
  238. entries, done, err := cursor.Next()
  239. if err != nil {
  240. return err
  241. }
  242. for _, e := range entries {
  243. row, err := decodeRow(e.Value)
  244. if err != nil {
  245. return err
  246. }
  247. stop, err := fn(row)
  248. if err != nil {
  249. return err
  250. }
  251. if stop {
  252. return nil
  253. }
  254. }
  255. if done {
  256. return nil
  257. }
  258. }
  259. })
  260. }
  261. // rowWithLSNVisitFunc is like rowVisitFunc but also passes the durable row LSN.
  262. type rowWithLSNVisitFunc func(row Row, lsn uint64) (stop bool, err error)
  263. // scanRowsWithLSN streams a table's rows together with their durable LSNs. It
  264. // is used by buffered transactions to capture a per-row read set for
  265. // compare-and-swap validation at commit.
  266. func (m *TableManager) scanRowsWithLSN(table string, fn rowWithLSNVisitFunc) error {
  267. return m.pool.WithClient(func(client *KVClient) (retErr error) {
  268. cursor, err := client.ScanWithLimit([]byte(m.dataPrefix(table)), scanPageSize)
  269. if err != nil {
  270. return err
  271. }
  272. defer func() {
  273. if err := cursor.Close(); retErr == nil {
  274. retErr = err
  275. }
  276. }()
  277. for {
  278. entries, done, err := cursor.Next()
  279. if err != nil {
  280. return err
  281. }
  282. for _, e := range entries {
  283. row, err := decodeRow(e.Value)
  284. if err != nil {
  285. return err
  286. }
  287. stop, err := fn(row, e.LSN)
  288. if err != nil {
  289. return err
  290. }
  291. if stop {
  292. return nil
  293. }
  294. }
  295. if done {
  296. return nil
  297. }
  298. }
  299. })
  300. }
  301. // scanRowsAtPrefix streams the rows under an explicit data prefix together with
  302. // their keys and durable LSNs. A transaction uses it when the rows of a table
  303. // still live under an older name because RENAME TABLE defers moving them to the
  304. // commit.
  305. func (m *TableManager) scanRowsAtPrefix(prefix string, fn func(key string, row Row, lsn uint64) (stop bool, err error)) error {
  306. return m.pool.WithClient(func(client *KVClient) (retErr error) {
  307. cursor, err := client.ScanWithLimit([]byte(prefix), scanPageSize)
  308. if err != nil {
  309. return err
  310. }
  311. defer func() {
  312. if err := cursor.Close(); retErr == nil {
  313. retErr = err
  314. }
  315. }()
  316. for {
  317. entries, done, err := cursor.Next()
  318. if err != nil {
  319. return err
  320. }
  321. for _, e := range entries {
  322. row, err := decodeRow(e.Value)
  323. if err != nil {
  324. return err
  325. }
  326. stop, err := fn(string(e.Key), row, e.LSN)
  327. if err != nil {
  328. return err
  329. }
  330. if stop {
  331. return nil
  332. }
  333. }
  334. if done {
  335. return nil
  336. }
  337. }
  338. })
  339. }
  340. // getKeyWithLSN reads and decodes a row by its explicit durable key.
  341. func (m *TableManager) getKeyWithLSN(key string) (Row, uint64, error) {
  342. var value []byte
  343. var lsn uint64
  344. err := m.pool.WithClient(func(c *KVClient) error {
  345. res, err := c.Get([]byte(key))
  346. if err != nil {
  347. return err
  348. }
  349. value = res.Value
  350. lsn = res.LSN
  351. return nil
  352. })
  353. if err != nil {
  354. if err == ErrKeyNotFound {
  355. return nil, 0, ErrKeyNotFound
  356. }
  357. return nil, 0, err
  358. }
  359. row, err := decodeRow(value)
  360. if err != nil {
  361. return nil, 0, fmt.Errorf("failed to parse row: %w", err)
  362. }
  363. return row, lsn, nil
  364. }
  365. // scanCountKeys counts the durable rows of table using a key-only scan so row
  366. // values are never pulled across the wire. It is used for first-time COUNT(*)
  367. // derivation.
  368. func (m *TableManager) scanCountKeys(table string) (int, error) {
  369. count := 0
  370. err := m.pool.WithClient(func(client *KVClient) (retErr error) {
  371. cursor, err := client.ScanKeys([]byte(m.dataPrefix(table)))
  372. if err != nil {
  373. return err
  374. }
  375. defer func() {
  376. if err := cursor.Close(); retErr == nil {
  377. retErr = err
  378. }
  379. }()
  380. for {
  381. entries, done, err := cursor.Next()
  382. if err != nil {
  383. return err
  384. }
  385. count += len(entries)
  386. if done {
  387. return nil
  388. }
  389. }
  390. })
  391. return count, err
  392. }
  393. // CountFast returns the exact number of rows in a table. The count is derived
  394. // from durable rows on first use (recovering across restarts) and then
  395. // maintained incrementally by the write paths, so repeated COUNT(*) queries
  396. // avoid a full table scan. It intentionally does not persist a counter to KV:
  397. // the KV layer has no atomic increment primitive, and a durable counter that
  398. // could diverge from the rows on crash would be worse than a lazily-derived,
  399. // always-exact value. The cost is one key-only scan the first time COUNT(*) is
  400. // issued after startup.
  401. func (m *TableManager) CountFast(table string) (int, error) {
  402. key := strings.ToLower(table)
  403. tableSchema, err := m.schema.GetSchema(table)
  404. if err != nil {
  405. return 0, err
  406. }
  407. // Cached read path: if the count is initialized for the current table
  408. // generation, return it without taking any table lock.
  409. m.cacheMu.Lock()
  410. if m.countGeneration[key].Equal(tableSchema.CreatedAt) {
  411. if m.countsInit[key] {
  412. n := m.counts[key]
  413. m.cacheMu.Unlock()
  414. return n, nil
  415. }
  416. } else {
  417. delete(m.counts, key)
  418. delete(m.countsInit, key)
  419. m.countGeneration[key] = tableSchema.CreatedAt
  420. }
  421. m.cacheMu.Unlock()
  422. // First derivation: hold the table write lock so the key-only scan is
  423. // exact against concurrent writes.
  424. tl := m.tableLock(key)
  425. tl.Lock()
  426. defer tl.Unlock()
  427. m.cacheMu.Lock()
  428. if !m.countGeneration[key].Equal(tableSchema.CreatedAt) {
  429. delete(m.counts, key)
  430. delete(m.countsInit, key)
  431. m.countGeneration[key] = tableSchema.CreatedAt
  432. }
  433. if m.countsInit[key] {
  434. n := m.counts[key]
  435. m.cacheMu.Unlock()
  436. return n, nil
  437. }
  438. m.cacheMu.Unlock()
  439. count, err := m.scanCountKeys(table)
  440. if err != nil {
  441. return 0, err
  442. }
  443. m.cacheMu.Lock()
  444. m.counts[key] = count
  445. m.countsInit[key] = true
  446. m.cacheMu.Unlock()
  447. return count, nil
  448. }
  449. // countInitialized reports whether the derived count cache is initialized for
  450. // the table at this instant. Write paths capture it before their KV write so a
  451. // concurrent first derivation does not double-count the just-written row.
  452. func (m *TableManager) countInitialized(table string) bool {
  453. key := strings.ToLower(table)
  454. m.cacheMu.Lock()
  455. init := m.countsInit[key]
  456. m.cacheMu.Unlock()
  457. return init
  458. }
  459. // incrCount adjusts the derived per-table row count. wasInit reports whether
  460. // the count was already initialized before the corresponding write, so a count
  461. // that was not yet initialized is left to be re-derived from durable rows
  462. // (which already reflect the write) on next use.
  463. func (m *TableManager) incrCount(table string, generation time.Time, delta int, wasInit bool) {
  464. key := strings.ToLower(table)
  465. m.cacheMu.Lock()
  466. if !m.countGeneration[key].Equal(generation) {
  467. delete(m.counts, key)
  468. delete(m.countsInit, key)
  469. m.countGeneration[key] = generation
  470. }
  471. if wasInit && m.countsInit[key] {
  472. m.counts[key] += delta
  473. }
  474. if !wasInit {
  475. // The count was not initialized before the write, so a concurrent first
  476. // derivation may have missed the just-written row. Invalidate to force
  477. // an exact re-derivation on the next COUNT(*).
  478. delete(m.countsInit, key)
  479. }
  480. m.cacheMu.Unlock()
  481. }
  482. // dataKey returns the key for a row.
  483. func (m *TableManager) dataKey(table, pk string) string {
  484. return fmt.Sprintf("%s:_data:%s:%s", m.database, strings.ToLower(table), pk)
  485. }
  486. // dataPrefix returns the prefix for all rows in a table.
  487. func (m *TableManager) dataPrefix(table string) string {
  488. return fmt.Sprintf("%s:_data:%s:", m.database, strings.ToLower(table))
  489. }
  490. // prepareInsert validates and normalizes an insert row, generating the ROWID
  491. // when required. It returns the normalized row and the full data key without
  492. // writing anything, so both the autocommit path (compare-and-swap) and the
  493. // buffered transaction path (staging) can share it.
  494. func (m *TableManager) prepareInsert(table string, row Row) (Row, string, error) {
  495. schema, err := m.schema.GetSchema(table)
  496. if err != nil {
  497. return nil, "", err
  498. }
  499. return m.prepareInsertWithSchema(table, schema, row)
  500. }
  501. // prepareInsertWithSchema is prepareInsert against a caller-supplied schema, so
  502. // a transaction normalizes rows with the catalog it can see, including a table
  503. // it created or altered in the open transaction.
  504. func (m *TableManager) prepareInsertWithSchema(table string, schema *Schema, row Row) (Row, string, error) {
  505. normalizedRow, key, _, err := m.normalizeInsertRow(table, schema, row)
  506. if err != nil {
  507. return nil, "", err
  508. }
  509. return normalizedRow, key, nil
  510. }
  511. // normalizeInsertRow completes a row image for an insert: it copies the caller's
  512. // columns case-insensitively, applies catalog defaults, assigns the ROWID (or
  513. // the INTEGER PRIMARY KEY rowid alias), encodes the primary key, and validates
  514. // the row constraints. It is shared by the point insert and bulk insert paths so
  515. // both key rows identically. The returned rowid is the row's ROWID alias, or 0
  516. // when the caller must not treat the primary key as a rowid.
  517. func (m *TableManager) normalizeInsertRow(table string, schema *Schema, row Row) (Row, string, int64, error) {
  518. normalizedRow := make(Row)
  519. for _, col := range schema.Columns {
  520. for k, v := range row {
  521. if strings.EqualFold(k, col.Name) {
  522. normalizedRow[col.Name] = v
  523. break
  524. }
  525. }
  526. }
  527. for _, col := range schema.Columns {
  528. if _, ok := normalizedRow[col.Name]; ok {
  529. continue
  530. }
  531. value, hasDefault, err := m.schema.columnDefaultValue(col, m.schema.defaultNow())
  532. if err != nil {
  533. return nil, "", 0, err
  534. }
  535. if hasDefault {
  536. normalizedRow[col.Name] = value
  537. }
  538. }
  539. // Only a single-column INTEGER PRIMARY KEY is a ROWID alias. A composite key
  540. // is never an alias, so its rows always carry an engine-assigned _rowid_.
  541. var rowid int64
  542. if schema.IsSingleColumnPrimaryKey() && !schema.UsesSyntheticRowID() {
  543. pkColumn := schema.PrimaryKey
  544. pkCol, _ := schema.GetColumn(pkColumn)
  545. if pkCol != nil && isIntegerType(pkCol.Type) {
  546. pkValue := normalizedRow[pkColumn]
  547. if pkValue == nil {
  548. nextRowID, err := m.schema.GetNextRowID(table)
  549. if err != nil {
  550. return nil, "", 0, err
  551. }
  552. rowid = nextRowID
  553. normalizedRow[pkColumn] = rowid
  554. } else {
  555. switch v := pkValue.(type) {
  556. case int64:
  557. rowid = v
  558. case float64:
  559. if math.Trunc(v) != v {
  560. return nil, "", 0, fmt.Errorf("invalid integer primary key: %v", v)
  561. }
  562. rowid = int64(v)
  563. case int:
  564. rowid = int64(v)
  565. default:
  566. rowid = 0
  567. }
  568. if rowid > 0 {
  569. if err := m.schema.UpdateMaxRowID(table, rowid); err != nil {
  570. return nil, "", 0, err
  571. }
  572. }
  573. }
  574. }
  575. }
  576. if rowid > 0 {
  577. normalizedRow["_rowid_"] = rowid
  578. } else {
  579. newRowID, err := m.schema.GetNextRowID(table)
  580. if err != nil {
  581. return nil, "", 0, err
  582. }
  583. normalizedRow["_rowid_"] = newRowID
  584. }
  585. key, err := schema.PrimaryKeyForRow(normalizedRow)
  586. if err != nil {
  587. return nil, "", 0, err
  588. }
  589. if err := m.schema.validateRowConstraints(schema, normalizedRow); err != nil {
  590. return nil, "", 0, err
  591. }
  592. // Callers read the resolved key back from the row they passed in: RETURNING
  593. // needs an auto-assigned INTEGER PRIMARY KEY, and a composite table needs key
  594. // components that came from a catalog DEFAULT because the conflict-matching
  595. // and fetch paths run before the next storage call.
  596. for _, column := range schema.PrimaryKeyList() {
  597. if value, ok := normalizedRow[column]; ok {
  598. row[column] = value
  599. }
  600. }
  601. return normalizedRow, m.dataKey(table, key), rowid, nil
  602. }
  603. // Insert inserts a new row. The duplicate check and write are one atomic
  604. // compare-and-swap so concurrent inserts of the same primary key cannot both
  605. // persist. The shared table gate is acquired before the key's striped lock so
  606. // a queued scan writer cannot invert the lock order with point operations.
  607. func (m *TableManager) Insert(table string, row Row) error {
  608. _, err := m.InsertWithRowID(table, row)
  609. return err
  610. }
  611. // InsertWithRowID returns the actual row identifier, never a concurrent counter.
  612. func (m *TableManager) InsertWithRowID(table string, row Row) (int64, error) {
  613. nr, key, err := m.prepareInsert(table, row)
  614. if err != nil {
  615. return 0, err
  616. }
  617. rowid, _ := rowIDFromRow(nr)
  618. wasInit := m.countInitialized(table)
  619. // Foreign-key validation scans the parent (and, for a parent change, the
  620. // child) rows. Take the foreign-key write gate before the table gate so a
  621. // concurrent write on the other side of the constraint cannot interleave and
  622. // so the lock order stays foreign-key gate -> table gate everywhere.
  623. unlockFK, err := m.lockForeignKeyWrites(table)
  624. if err != nil {
  625. return 0, err
  626. }
  627. defer unlockFK()
  628. // Point writers share this gate with each other. Transaction commits and
  629. // scan-based writes take it exclusively, so generation validation and cache
  630. // publication are ordered without serializing writes to different keys.
  631. // A UNIQUE index forces the exclusive gate so the validating scan below
  632. // cannot race another writer (or a concurrent CREATE UNIQUE INDEX).
  633. unlock, uniq, err := m.lockForWrite(table)
  634. if err != nil {
  635. return 0, err
  636. }
  637. defer unlock()
  638. // prepareInsert normalized the row before this gate was held, so a
  639. // concurrent ADD COLUMN may have published a column the row image predates.
  640. // Re-apply the schema that is current under the gate; schema DDL needs the
  641. // exclusive form of this gate, so it cannot change again before the write.
  642. schema, err := m.schema.GetSchema(table)
  643. if err != nil {
  644. return 0, err
  645. }
  646. if err := m.schema.applySchemaDefaults(schema, nr); err != nil {
  647. return 0, err
  648. }
  649. if err := m.schema.validateChecks(schema, nr); err != nil {
  650. return 0, err
  651. }
  652. if err := m.validateInsertForeignKeys(schema, []Row{nr}); err != nil {
  653. return 0, err
  654. }
  655. data, err := encodeRow(nr)
  656. if err != nil {
  657. return 0, fmt.Errorf("failed to serialize row: %w", err)
  658. }
  659. var uniquePlan uniqueCachePlan
  660. if uniq {
  661. uniquePlan, err = m.prepareUniqueRows(table, map[string]*overlayEntry{key: {row: nr}})
  662. if err != nil {
  663. return 0, err
  664. }
  665. }
  666. st := m.stripeKey(key)
  667. st.Lock()
  668. defer st.Unlock()
  669. committed, err := m.compareWritePoint(
  670. []CompareCheck{{Key: []byte(key), LSN: 0}},
  671. []BatchOp{{Op: batchPut, Key: []byte(key), Value: data}},
  672. )
  673. if err != nil {
  674. m.invalidateWriteFailure(table)
  675. return 0, err
  676. }
  677. if !committed {
  678. return 0, &PrimaryKeyViolationError{Table: table, Key: strings.TrimPrefix(key, m.dataPrefix(table))}
  679. }
  680. m.applyUniquePlan(uniquePlan, nil)
  681. if err := m.updateIndexesForRow(table, nr, true, key); err != nil {
  682. return 0, err
  683. }
  684. // Publish derived index state before its generations. A reader that races
  685. // with publication either sees the old generation and aborts or sees the
  686. // complete new state.
  687. if err := m.bumpIndexPredicates(table, nr); err != nil {
  688. return 0, err
  689. }
  690. m.bumpGeneration(table)
  691. m.incrCount(table, schema.CreatedAt, 1, wasInit)
  692. return rowid, nil
  693. }
  694. // bulkBatchByteBudget bounds a single atomic BATCH_WRITE payload below the
  695. // PKBFI frame limit so a bulk insert never emits a frame the server rejects.
  696. // Each op contributes 12 header bytes plus its key and value.
  697. const bulkBatchByteBudget = 60 * 1024 * 1024
  698. // chunkBatchOps splits ops into atomic BATCH_WRITE chunks bounded by both the
  699. // PKBFI operation-count limit and the frame-size limit. Each chunk is a slice
  700. // of the backing array, valid until the next append to ops.
  701. func chunkBatchOps(ops []BatchOp) [][]BatchOp {
  702. var chunks [][]BatchOp
  703. for i := 0; i < len(ops); {
  704. end := i + maxOperations
  705. if end > len(ops) {
  706. end = len(ops)
  707. }
  708. bytes := 0
  709. j := i
  710. for j < end {
  711. sz := 12 + len(ops[j].Key) + len(ops[j].Value)
  712. if j > i && bytes+sz > bulkBatchByteBudget {
  713. break
  714. }
  715. bytes += sz
  716. j++
  717. }
  718. if j == i {
  719. j = i + 1
  720. }
  721. chunks = append(chunks, ops[i:j])
  722. i = j
  723. }
  724. return chunks
  725. }
  726. // InsertBulk inserts multiple rows efficiently using atomic BATCH_WRITE chunks
  727. // bounded by the PKBFI operation-count and frame-size limits. Skips per-row
  728. // duplicate checks (caller must ensure uniqueness). Used by INSERT ... SELECT.
  729. func (m *TableManager) InsertBulk(table string, rows []Row) (int, error) {
  730. count, _, err := m.InsertBulkWithLastRowID(table, rows)
  731. return count, err
  732. }
  733. // InsertBulkWithLastRowID is InsertBulk, additionally returning the ROWID of the
  734. // last persisted row (0 when nothing persisted).
  735. func (m *TableManager) InsertBulkWithLastRowID(table string, rows []Row) (int, int64, error) {
  736. if len(rows) == 0 {
  737. return 0, 0, nil
  738. }
  739. unlockFK, err := m.lockForeignKeyWrites(table)
  740. if err != nil {
  741. return 0, 0, err
  742. }
  743. defer unlockFK()
  744. tl := m.tableLock(table)
  745. tl.Lock()
  746. defer tl.Unlock()
  747. schema, err := m.schema.GetSchema(table)
  748. if err != nil {
  749. return 0, 0, err
  750. }
  751. wasInit := m.countInitialized(table)
  752. // Normalize rows, assigning the ROWID and encoding the primary key exactly as
  753. // the point insert path does.
  754. normalized := make([]Row, 0, len(rows))
  755. dataKeys := make([]string, 0, len(rows))
  756. for _, row := range rows {
  757. nr, key, _, err := m.normalizeInsertRow(table, schema, row)
  758. if err != nil {
  759. return 0, 0, err
  760. }
  761. normalized = append(normalized, nr)
  762. dataKeys = append(dataKeys, key)
  763. }
  764. // Every row of the batch is visible to the others, so a self-referential
  765. // multi-row insert may reference a sibling that is written in the same
  766. // atomic batch.
  767. if err := m.validateInsertForeignKeys(schema, normalized); err != nil {
  768. return 0, 0, err
  769. }
  770. // Serialize all rows into batch operations. A parallel slice keeps the
  771. // normalized Row for each op for index maintenance after the write.
  772. ops := make([]BatchOp, 0, len(normalized))
  773. encoded := make([]Row, 0, len(normalized))
  774. for i, nr := range normalized {
  775. data, err := encodeRow(nr)
  776. if err != nil {
  777. return 0, 0, err
  778. }
  779. ops = append(ops, BatchOp{Op: batchPut, Key: []byte(dataKeys[i]), Value: data})
  780. encoded = append(encoded, nr)
  781. }
  782. keys := make([][]byte, len(ops))
  783. seen := make(map[string]struct{}, len(ops))
  784. for i, op := range ops {
  785. key := string(op.Key)
  786. if _, duplicate := seen[key]; duplicate {
  787. return 0, 0, &PrimaryKeyViolationError{Table: table, Key: key}
  788. }
  789. seen[key] = struct{}{}
  790. keys[i] = op.Key
  791. }
  792. existing := make([]bool, len(keys))
  793. if err := m.pool.WithClient(func(client *KVClient) error {
  794. for start := 0; start < len(keys); start += maxOperations {
  795. end := start + maxOperations
  796. if end > len(keys) {
  797. end = len(keys)
  798. }
  799. found, err := client.ExistsMany(keys[start:end])
  800. if err != nil {
  801. return err
  802. }
  803. copy(existing[start:end], found)
  804. }
  805. return nil
  806. }); err != nil {
  807. return 0, 0, err
  808. }
  809. for i, found := range existing {
  810. if found {
  811. return 0, 0, &PrimaryKeyViolationError{Table: table, Key: string(ops[i].Key)}
  812. }
  813. }
  814. var uniquePlan uniqueCachePlan
  815. unique, err := m.hasUniqueIndex(table)
  816. if err != nil {
  817. return 0, 0, err
  818. }
  819. if unique {
  820. uniqueEntries := make(map[string]*overlayEntry, len(encoded))
  821. for i, row := range encoded {
  822. uniqueEntries[string(ops[i].Key)] = &overlayEntry{row: row}
  823. }
  824. uniquePlan, err = m.prepareUniqueRows(table, uniqueEntries)
  825. if err != nil {
  826. return 0, 0, err
  827. }
  828. }
  829. // Write rows in atomic BATCH_WRITE chunks. Maintain in-memory indexes only
  830. // for rows that actually persisted, so a partial failure cannot leave an
  831. // already-built index stale.
  832. var firstErr error
  833. numOK := 0
  834. for _, chunk := range chunkBatchOps(ops) {
  835. err := m.pool.WithClient(func(c *KVClient) error {
  836. _, err := c.BatchWrite(chunk, nil)
  837. return err
  838. })
  839. if err != nil {
  840. if firstErr == nil {
  841. firstErr = err
  842. }
  843. break
  844. }
  845. numOK += len(chunk)
  846. }
  847. // Maintain indexes for the rows that persisted (the first numOK ops).
  848. if len(uniquePlan) != 0 {
  849. accepted := make(map[string]bool, numOK)
  850. for i := 0; i < numOK; i++ {
  851. accepted[string(ops[i].Key)] = true
  852. }
  853. m.applyUniquePlan(uniquePlan, accepted)
  854. }
  855. for i := 0; i < numOK; i++ {
  856. if err := m.updateIndexesForRow(table, encoded[i], true, string(ops[i].Key)); err != nil {
  857. return numOK, 0, err
  858. }
  859. }
  860. if numOK > 0 {
  861. m.bumpGeneration(table)
  862. if err := m.bumpIndexPredicates(table, encoded[:numOK]...); err != nil {
  863. return numOK, 0, err
  864. }
  865. }
  866. m.incrCount(table, schema.CreatedAt, numOK, wasInit)
  867. if firstErr != nil {
  868. m.invalidateWriteFailure(table)
  869. }
  870. var lastRowID int64
  871. if numOK > 0 {
  872. lastRowID, _ = rowIDFromRow(encoded[numOK-1])
  873. }
  874. return numOK, lastRowID, firstErr
  875. }
  876. // updateIndexesForRow adds or removes entries from already-built in-memory
  877. // indexes. Index entries are rebuildable from durable row data, so this method
  878. // intentionally does not write idx:* keys to KV.
  879. func (m *TableManager) updateIndexesForRow(table string, row Row, add bool, actualKey string) error {
  880. indexes, err := m.schema.ListTableIndexes(table)
  881. if err != nil || len(indexes) == 0 {
  882. return err
  883. }
  884. rowid, ok := rowIDFromRow(row)
  885. if !ok {
  886. return nil
  887. }
  888. tableKey := strings.ToLower(table)
  889. m.cacheMu.Lock()
  890. if keys, initialized := m.rowKeyCache[tableKey]; initialized {
  891. pk := strings.TrimPrefix(actualKey, m.dataPrefix(table))
  892. reverse := m.keyRowCache[tableKey]
  893. if add {
  894. keys[rowid] = pk
  895. reverse[pk] = rowid
  896. } else {
  897. delete(keys, rowid)
  898. delete(reverse, pk)
  899. }
  900. }
  901. m.cacheMu.Unlock()
  902. for _, idx := range indexes {
  903. indexName := strings.ToLower(idx.Name)
  904. m.cacheMu.RLock()
  905. _, initialized := m.indexCache[indexName]
  906. m.cacheMu.RUnlock()
  907. if !initialized {
  908. continue
  909. }
  910. colValue, err := m.buildIndexValue(row, idx.Columns)
  911. if err != nil {
  912. return err
  913. }
  914. if add {
  915. m.AddIndexEntry(idx.Name, colValue, rowid)
  916. } else {
  917. m.RemoveIndexEntry(idx.Name, colValue, rowid)
  918. }
  919. }
  920. return nil
  921. }
  922. // Select retrieves rows from a table by scanning durable rows and collecting
  923. // only matching rows.
  924. func (m *TableManager) Select(table string, filter func(Row) bool) ([]Row, error) {
  925. tl := m.tableLock(table)
  926. tl.RLock()
  927. defer tl.RUnlock()
  928. return m.selectRows(table, filter)
  929. }
  930. // selectRows scans a table while the caller holds its shared or exclusive gate.
  931. func (m *TableManager) selectRows(table string, filter func(Row) bool) ([]Row, error) {
  932. if !m.schema.TableExists(table) {
  933. return nil, fmt.Errorf("table not found: %s", table)
  934. }
  935. rows := make([]Row, 0)
  936. err := m.scanRows(table, func(row Row) (bool, error) {
  937. if filter == nil || filter(row) {
  938. rows = append(rows, row)
  939. }
  940. return false, nil
  941. })
  942. if err != nil {
  943. return nil, err
  944. }
  945. return rows, nil
  946. }
  947. func cloneRow(row Row) Row {
  948. if row == nil {
  949. return nil
  950. }
  951. cloned := make(Row, len(row))
  952. for k, v := range row {
  953. cloned[k] = v
  954. }
  955. return cloned
  956. }
  957. // SelectWithLimit retrieves rows with limit and offset, applying filter/offset
  958. // while scanning and closing the scan early once the limit is reached.
  959. func (m *TableManager) SelectWithLimit(table string, filter func(Row) bool, limit, offset int) ([]Row, error) {
  960. tl := m.tableLock(table)
  961. tl.RLock()
  962. defer tl.RUnlock()
  963. if !m.schema.TableExists(table) {
  964. return nil, fmt.Errorf("table not found: %s", table)
  965. }
  966. rows := make([]Row, 0)
  967. skipped := 0
  968. pageSize := scanPageSize
  969. if limit > 0 {
  970. desired := limit
  971. if offset > 0 {
  972. if offset >= scanPageSize-desired {
  973. desired = scanPageSize
  974. } else {
  975. desired += offset
  976. }
  977. }
  978. if desired < 1 {
  979. desired = 1
  980. }
  981. if desired < pageSize {
  982. pageSize = desired
  983. }
  984. }
  985. err := m.scanRowsWithPageSize(table, uint32(pageSize), func(row Row) (bool, error) {
  986. if filter != nil && !filter(row) {
  987. return false, nil
  988. }
  989. if skipped < offset {
  990. skipped++
  991. return false, nil
  992. }
  993. rows = append(rows, row)
  994. return limit > 0 && len(rows) >= limit, nil
  995. })
  996. if err != nil {
  997. return nil, err
  998. }
  999. return rows, nil
  1000. }
  1001. // Update updates rows matching the filter.
  1002. func (m *TableManager) Update(table string, updates Row, filter func(Row) bool) (int, error) {
  1003. return m.updateLocked(table, func(Row) (Row, error) { return updates, nil }, filter)
  1004. }
  1005. // UpdateFunc updates rows matching the filter using a function to compute new values.
  1006. // The updateFn receives the current row and returns the updates to apply.
  1007. func (m *TableManager) UpdateFunc(table string, updateFn func(Row) (Row, error), filter func(Row) bool) (int, error) {
  1008. return m.updateLocked(table, updateFn, filter)
  1009. }
  1010. // updateLocked stages the complete update before one compare-batch publication.
  1011. // Evaluation, encoding, validation or I/O errors must never leave earlier rows
  1012. // committed, including when a primary key moves to a different durable key.
  1013. func (m *TableManager) updateLocked(table string, updateFn func(Row) (Row, error), filter func(Row) bool) (int, error) {
  1014. session := NewSession(m.schema, m)
  1015. if err := session.Begin(); err != nil {
  1016. return 0, err
  1017. }
  1018. defer session.Rollback()
  1019. count, err := session.UpdateFunc(table, updateFn, filter)
  1020. if err != nil {
  1021. return 0, err
  1022. }
  1023. if err := session.Commit(); err != nil {
  1024. return 0, err
  1025. }
  1026. return count, nil
  1027. }
  1028. // UpdateByPK updates one row without scanning the table. It uses the key's
  1029. // striped lock and a compare-and-swap write so a concurrent modification of the
  1030. // same row fails with a serialization error instead of being silently lost.
  1031. func (m *TableManager) UpdateByPK(table, pk string, updateFn func(Row) (Row, error)) (Row, bool, error) {
  1032. key := m.dataKey(table, pk)
  1033. unlockFK, err := m.lockForeignKeyWrites(table)
  1034. if err != nil {
  1035. return nil, false, err
  1036. }
  1037. defer unlockFK()
  1038. unlock, uniq, err := m.lockForWrite(table)
  1039. if err != nil {
  1040. return nil, false, err
  1041. }
  1042. defer unlock()
  1043. // Read the schema under the gate so validation sees every column a
  1044. // concurrent ADD COLUMN has published; the row itself is read below, also
  1045. // under the gate.
  1046. schema, err := m.schema.GetSchema(table)
  1047. if err != nil {
  1048. return nil, false, err
  1049. }
  1050. st := m.stripeKey(key)
  1051. st.Lock()
  1052. defer st.Unlock()
  1053. row, lsn, err := m.getByPKWithLSN(table, pk)
  1054. if err == ErrKeyNotFound {
  1055. return nil, false, nil
  1056. }
  1057. if err != nil {
  1058. return nil, false, err
  1059. }
  1060. oldRow := cloneRow(row)
  1061. updates, err := updateFn(row)
  1062. if err != nil {
  1063. return nil, false, err
  1064. }
  1065. for name, value := range updates {
  1066. for _, column := range schema.Columns {
  1067. if strings.EqualFold(name, column.Name) {
  1068. row[column.Name] = value
  1069. break
  1070. }
  1071. }
  1072. }
  1073. if err := m.schema.applySchemaDefaults(schema, row); err != nil {
  1074. return nil, false, err
  1075. }
  1076. if err := m.schema.validateChecks(schema, row); err != nil {
  1077. return nil, false, err
  1078. }
  1079. if err := m.validateInsertForeignKeys(schema, []Row{row}); err != nil {
  1080. return nil, false, err
  1081. }
  1082. if err := m.validateParentKeyRemoval(table, oldRow, row); err != nil {
  1083. return nil, false, err
  1084. }
  1085. data, err := encodeRow(row)
  1086. if err != nil {
  1087. return nil, false, err
  1088. }
  1089. var uniquePlan uniqueCachePlan
  1090. if uniq {
  1091. uniquePlan, err = m.prepareUniqueRows(table, map[string]*overlayEntry{key: {row: row}})
  1092. if err != nil {
  1093. return nil, false, err
  1094. }
  1095. }
  1096. committed, err := m.compareWritePoint(
  1097. []CompareCheck{{Key: []byte(key), LSN: lsn}},
  1098. []BatchOp{{Op: batchPut, Key: []byte(key), Value: data}},
  1099. )
  1100. if err != nil {
  1101. m.invalidateWriteFailure(table)
  1102. return nil, false, err
  1103. }
  1104. if !committed {
  1105. return nil, false, ErrSerialization
  1106. }
  1107. m.applyUniquePlan(uniquePlan, nil)
  1108. if err := m.updateIndexesForRow(table, oldRow, false, key); err != nil {
  1109. return nil, false, err
  1110. }
  1111. if err := m.updateIndexesForRow(table, row, true, key); err != nil {
  1112. return nil, false, err
  1113. }
  1114. if err := m.bumpIndexPredicates(table, oldRow, row); err != nil {
  1115. return nil, false, err
  1116. }
  1117. m.bumpGeneration(table)
  1118. return oldRow, true, nil
  1119. }
  1120. // Delete deletes rows matching the filter.
  1121. func (m *TableManager) Delete(table string, filter func(Row) bool) (int, error) {
  1122. session := NewSession(m.schema, m)
  1123. if err := session.Begin(); err != nil {
  1124. return 0, err
  1125. }
  1126. defer session.Rollback()
  1127. count, err := session.Delete(table, filter)
  1128. if err != nil {
  1129. return 0, err
  1130. }
  1131. if err := session.Commit(); err != nil {
  1132. return 0, err
  1133. }
  1134. return count, nil
  1135. }
  1136. // DeleteByPK deletes one row without scanning the table, using the key's
  1137. // striped lock and a compare-and-swap delete.
  1138. func (m *TableManager) DeleteByPK(table, pk string) (Row, bool, error) {
  1139. schema, err := m.schema.GetSchema(table)
  1140. if err != nil {
  1141. return nil, false, err
  1142. }
  1143. unlockFK, err := m.lockForeignKeyWrites(table)
  1144. if err != nil {
  1145. return nil, false, err
  1146. }
  1147. defer unlockFK()
  1148. key := m.dataKey(table, pk)
  1149. tl := m.tableLock(table)
  1150. tl.RLock()
  1151. defer tl.RUnlock()
  1152. st := m.stripeKey(key)
  1153. st.Lock()
  1154. defer st.Unlock()
  1155. wasInit := m.countInitialized(table)
  1156. row, lsn, err := m.getByPKWithLSN(table, pk)
  1157. if err == ErrKeyNotFound {
  1158. return nil, false, nil
  1159. }
  1160. if err != nil {
  1161. return nil, false, err
  1162. }
  1163. if err := m.validateParentKeyRemoval(table, row, nil); err != nil {
  1164. return nil, false, err
  1165. }
  1166. committed, err := m.compareWritePoint(
  1167. []CompareCheck{{Key: []byte(key), LSN: lsn}},
  1168. []BatchOp{{Op: batchDelete, Key: []byte(key)}},
  1169. )
  1170. if err != nil {
  1171. m.invalidateWriteFailure(table)
  1172. return nil, false, err
  1173. }
  1174. if !committed {
  1175. return nil, false, ErrSerialization
  1176. }
  1177. m.removeUniqueKey(table, key)
  1178. if err := m.updateIndexesForRow(table, row, false, key); err != nil {
  1179. return nil, false, err
  1180. }
  1181. if err := m.bumpIndexPredicates(table, row); err != nil {
  1182. return nil, false, err
  1183. }
  1184. m.bumpGeneration(table)
  1185. m.incrCount(table, schema.CreatedAt, -1, wasInit)
  1186. return row, true, nil
  1187. }
  1188. // GetByPK retrieves a row by primary key. Point reads take only the key's
  1189. // striped lock so reads of different keys progress concurrently.
  1190. func (m *TableManager) GetByPK(table string, pk string) (Row, error) {
  1191. key := m.dataKey(table, pk)
  1192. st := m.stripeKey(key)
  1193. st.Lock()
  1194. defer st.Unlock()
  1195. if !m.schema.TableExists(table) {
  1196. return nil, fmt.Errorf("table not found: %s", table)
  1197. }
  1198. row, _, err := m.getByPKWithLSN(table, pk)
  1199. return row, err
  1200. }
  1201. // getByPKWithLSN reads a row by primary key and returns its KV LSN (0 when
  1202. // absent). It performs no locking; callers must hold the appropriate striped
  1203. // or table lock.
  1204. func (m *TableManager) getByPKWithLSN(table, pk string) (Row, uint64, error) {
  1205. key := m.dataKey(table, pk)
  1206. var value []byte
  1207. var lsn uint64
  1208. err := m.pool.WithClient(func(c *KVClient) error {
  1209. res, err := c.Get([]byte(key))
  1210. if err != nil {
  1211. return err
  1212. }
  1213. value = res.Value
  1214. lsn = res.LSN
  1215. return nil
  1216. })
  1217. if err != nil {
  1218. if err == ErrKeyNotFound {
  1219. return nil, 0, ErrKeyNotFound
  1220. }
  1221. return nil, 0, err
  1222. }
  1223. row, err := decodeRow(value)
  1224. if err != nil {
  1225. return nil, 0, fmt.Errorf("failed to parse row: %w", err)
  1226. }
  1227. return row, lsn, nil
  1228. }
  1229. // Count returns the number of rows in a table matching the filter.
  1230. func (m *TableManager) Count(table string, filter func(Row) bool) (int, error) {
  1231. tl := m.tableLock(table)
  1232. tl.RLock()
  1233. defer tl.RUnlock()
  1234. if !m.schema.TableExists(table) {
  1235. return 0, fmt.Errorf("table not found: %s", table)
  1236. }
  1237. count := 0
  1238. err := m.scanRows(table, func(row Row) (bool, error) {
  1239. if filter == nil || filter(row) {
  1240. count++
  1241. }
  1242. return false, nil
  1243. })
  1244. if err != nil {
  1245. return 0, err
  1246. }
  1247. return count, nil
  1248. }
  1249. // Truncate removes all rows from a table.
  1250. func (m *TableManager) Truncate(table string) (int, error) {
  1251. return m.Delete(table, nil)
  1252. }
  1253. // isIntegerType checks if a type name is an integer type.
  1254. func isIntegerType(typeName string) bool {
  1255. t := strings.ToUpper(typeName)
  1256. switch t {
  1257. case "INTEGER", "INT", "SMALLINT", "BIGINT", "TINYINT", "MEDIUMINT":
  1258. return true
  1259. }
  1260. return false
  1261. }
  1262. // IsRowIDColumn checks if a column name is a ROWID alias.
  1263. func IsRowIDColumn(name string) bool {
  1264. n := strings.ToLower(name)
  1265. return n == "rowid" || n == "oid" || n == "_rowid_"
  1266. }
  1267. // Index entry methods - leveraging radix trie for prefix-based lookups
  1268. // Format: {database}:idx:{index_name}:{column_value} → JSON array of rowids
  1269. // indexEntryKey returns the key for an index entry.
  1270. func (m *TableManager) indexEntryKey(indexName string, colValue interface{}) string {
  1271. return fmt.Sprintf("%s:idx:%s:%s", m.database, strings.ToLower(indexName), formatIndexValue(colValue))
  1272. }
  1273. // indexPrefix returns the prefix for all entries of an index.
  1274. func (m *TableManager) indexPrefix(indexName string) string {
  1275. return fmt.Sprintf("%s:idx:%s:", m.database, strings.ToLower(indexName))
  1276. }
  1277. func formatIndexValue(value interface{}) string {
  1278. // Equality predicates compare numeric values (including numeric text) as
  1279. // float64. Use the same equivalence classes without decimal rounding.
  1280. // Index hits are candidates: the executor still evaluates the predicate.
  1281. var number float64
  1282. switch v := value.(type) {
  1283. case float64:
  1284. number = v
  1285. case int64:
  1286. number = float64(v)
  1287. case int:
  1288. number = float64(v)
  1289. case bool:
  1290. if v {
  1291. return "1"
  1292. }
  1293. return "0"
  1294. case []byte:
  1295. return formatIndexValue(string(v))
  1296. case string:
  1297. parsed, err := strconv.ParseFloat(v, 64)
  1298. if err != nil {
  1299. return v
  1300. }
  1301. number = parsed
  1302. default:
  1303. return fmt.Sprintf("%v", v)
  1304. }
  1305. if number == 0 {
  1306. return "0"
  1307. }
  1308. return strconv.FormatFloat(number, 'g', -1, 64)
  1309. }
  1310. func rowIDFromRow(row Row) (int64, bool) {
  1311. switch v := row["_rowid_"].(type) {
  1312. case int64:
  1313. return v, true
  1314. case int:
  1315. return int64(v), true
  1316. case float64:
  1317. return int64(v), true
  1318. default:
  1319. return 0, false
  1320. }
  1321. }
  1322. func (m *TableManager) ensureIndex(index *Index) error {
  1323. indexKey := strings.ToLower(index.Name)
  1324. m.cacheMu.RLock()
  1325. disabled := m.disabledIndexes[indexKey]
  1326. _, initialized := m.indexCache[indexKey]
  1327. m.cacheMu.RUnlock()
  1328. if disabled {
  1329. return nil
  1330. }
  1331. if initialized {
  1332. return nil
  1333. }
  1334. // Serialize index build against writes to the same table so the derived
  1335. // entries cannot miss a concurrently-inserted row.
  1336. table := index.Table
  1337. key := strings.ToLower(table)
  1338. tl := m.tableLock(key)
  1339. tl.Lock()
  1340. defer tl.Unlock()
  1341. m.cacheMu.RLock()
  1342. disabled = m.disabledIndexes[indexKey]
  1343. _, initialized = m.indexCache[indexKey]
  1344. m.cacheMu.RUnlock()
  1345. if disabled {
  1346. return nil
  1347. }
  1348. if initialized {
  1349. return nil
  1350. }
  1351. tableSchema, err := m.schema.GetSchema(table)
  1352. if err != nil {
  1353. return err
  1354. }
  1355. values := make(map[string][]int64)
  1356. rowKeys := make(map[int64]string)
  1357. if err := m.scanRows(table, func(row Row) (bool, error) {
  1358. rowid, ok := rowIDFromRow(row)
  1359. if !ok {
  1360. return false, nil
  1361. }
  1362. colValue, err := m.buildIndexValue(row, index.Columns)
  1363. if err != nil {
  1364. return true, err
  1365. }
  1366. valueKey := formatIndexValue(colValue)
  1367. pk, err := tableSchema.PrimaryKeyForRow(row)
  1368. if err != nil {
  1369. return true, err
  1370. }
  1371. values[valueKey] = append(values[valueKey], rowid)
  1372. rowKeys[rowid] = pk
  1373. return false, nil
  1374. }); err != nil {
  1375. return err
  1376. }
  1377. m.cacheMu.Lock()
  1378. if _, initialized := m.indexCache[indexKey]; !initialized {
  1379. m.installIndexCacheLocked(indexKey, key, values, rowKeys)
  1380. }
  1381. m.cacheMu.Unlock()
  1382. return nil
  1383. }
  1384. // AddIndexEntry adds a rowid to an in-memory index entry.
  1385. func (m *TableManager) AddIndexEntry(indexName string, colValue interface{}, rowid int64) error {
  1386. indexKey := strings.ToLower(indexName)
  1387. valueKey := formatIndexValue(colValue)
  1388. m.cacheMu.Lock()
  1389. defer m.cacheMu.Unlock()
  1390. values, ok := m.indexCache[indexKey]
  1391. if !ok {
  1392. return nil
  1393. }
  1394. rowids := values[valueKey]
  1395. for _, r := range rowids {
  1396. if r == rowid {
  1397. return nil
  1398. }
  1399. }
  1400. values[valueKey] = append(rowids, rowid)
  1401. if m.indexRowValues[indexKey] == nil {
  1402. m.indexRowValues[indexKey] = make(map[int64]string)
  1403. }
  1404. m.indexRowValues[indexKey][rowid] = valueKey
  1405. return nil
  1406. }
  1407. // RemoveIndexEntry removes a rowid from an in-memory index entry.
  1408. func (m *TableManager) RemoveIndexEntry(indexName string, colValue interface{}, rowid int64) error {
  1409. indexKey := strings.ToLower(indexName)
  1410. valueKey := formatIndexValue(colValue)
  1411. m.cacheMu.Lock()
  1412. defer m.cacheMu.Unlock()
  1413. m.removeIndexEntryLocked(indexKey, valueKey, rowid)
  1414. return nil
  1415. }
  1416. // LookupIndex returns rowids matching a column value using the index.
  1417. func (m *TableManager) LookupIndex(indexName string, colValue interface{}) ([]int64, error) {
  1418. index, err := m.schema.GetIndex(indexName)
  1419. if err != nil {
  1420. return nil, err
  1421. }
  1422. indexKey := strings.ToLower(indexName)
  1423. valueKey := formatIndexValue(colValue)
  1424. for {
  1425. if err := m.ensureIndex(index); err != nil {
  1426. return nil, err
  1427. }
  1428. m.cacheMu.RLock()
  1429. values, initialized := m.indexCache[indexKey]
  1430. disabled := m.disabledIndexes[indexKey]
  1431. rowids := append([]int64(nil), values[valueKey]...)
  1432. m.cacheMu.RUnlock()
  1433. if disabled {
  1434. return nil, fmt.Errorf("%w: %s is disabled", ErrIndexNotFound, indexName)
  1435. }
  1436. if initialized {
  1437. return rowids, nil
  1438. }
  1439. // A shared-gate commit invalidated the cache after ensureIndex.
  1440. }
  1441. }
  1442. // ClearIndex removes an index's in-memory entries and marks it disabled so a
  1443. // concurrent lookup cannot rebuild it after DROP but before the schema entry
  1444. // is removed. Index entries are derived from durable rows, so there is nothing
  1445. // durable to delete here.
  1446. func (m *TableManager) ClearIndex(indexName, tableName string, columns []string) error {
  1447. indexKey := strings.ToLower(indexName)
  1448. tableKey := strings.ToLower(tableName)
  1449. m.cacheMu.Lock()
  1450. delete(m.indexCache, indexKey)
  1451. delete(m.indexRowValues, indexKey)
  1452. delete(m.indexTable, indexKey)
  1453. delete(m.uniqueCache, indexKey)
  1454. m.disabledIndexes[indexKey] = true
  1455. rowKeysNeeded := false
  1456. for _, indexedTable := range m.indexTable {
  1457. if indexedTable == tableKey {
  1458. rowKeysNeeded = true
  1459. break
  1460. }
  1461. }
  1462. if !rowKeysNeeded {
  1463. delete(m.rowKeyCache, tableKey)
  1464. delete(m.keyRowCache, tableKey)
  1465. }
  1466. m.cacheMu.Unlock()
  1467. return nil
  1468. }
  1469. // BuildIndex builds index entries for all existing rows in a table.
  1470. func (m *TableManager) BuildIndex(indexName, tableName string, columns []string) error {
  1471. indexKey := strings.ToLower(indexName)
  1472. m.cacheMu.Lock()
  1473. delete(m.disabledIndexes, indexKey)
  1474. delete(m.indexCache, indexKey)
  1475. delete(m.indexRowValues, indexKey)
  1476. delete(m.indexTable, indexKey)
  1477. m.cacheMu.Unlock()
  1478. index, err := m.schema.GetIndex(indexName)
  1479. if err == nil {
  1480. return m.ensureIndex(index)
  1481. }
  1482. if !errors.Is(err, ErrIndexNotFound) {
  1483. return err
  1484. }
  1485. tableSchema, schemaErr := m.schema.GetSchema(tableName)
  1486. if schemaErr != nil {
  1487. return schemaErr
  1488. }
  1489. indexCols := make([]IndexColumn, len(columns))
  1490. for i, name := range columns {
  1491. indexCols[i] = IndexColumn{Name: name}
  1492. }
  1493. values := make(map[string][]int64)
  1494. rowKeys := make(map[int64]string)
  1495. if err := m.scanRows(tableName, func(row Row) (bool, error) {
  1496. rowid, ok := rowIDFromRow(row)
  1497. if !ok {
  1498. return false, nil
  1499. }
  1500. colValue, err := m.buildIndexValue(row, indexCols)
  1501. if err != nil {
  1502. return true, err
  1503. }
  1504. pk, err := tableSchema.PrimaryKeyForRow(row)
  1505. if err != nil {
  1506. return true, err
  1507. }
  1508. values[formatIndexValue(colValue)] = append(values[formatIndexValue(colValue)], rowid)
  1509. rowKeys[rowid] = pk
  1510. return false, nil
  1511. }); err != nil {
  1512. return err
  1513. }
  1514. m.cacheMu.Lock()
  1515. m.installIndexCacheLocked(indexKey, strings.ToLower(tableName), values, rowKeys)
  1516. m.cacheMu.Unlock()
  1517. return nil
  1518. }
  1519. // indexColumnValue resolves a single index column's value for a row. A plain
  1520. // column is looked up case-insensitively; an expression column is evaluated
  1521. // through the registered expression evaluator.
  1522. func (m *TableManager) indexColumnValue(row Row, col IndexColumn) (interface{}, error) {
  1523. if col.Expression != "" {
  1524. eval := m.expressionEvaluator()
  1525. if eval == nil {
  1526. return nil, fmt.Errorf("expression index column %q requires an expression evaluator", col.Expression)
  1527. }
  1528. return eval(col.Expression, row)
  1529. }
  1530. if v, ok := row[col.Name]; ok {
  1531. return v, nil
  1532. }
  1533. for k, v := range row {
  1534. if strings.EqualFold(k, col.Name) {
  1535. return v, nil
  1536. }
  1537. }
  1538. return nil, nil
  1539. }
  1540. // buildIndexValue creates the index key value from an index's columns. Single
  1541. // column values are formatted directly; composite values are joined with a NUL
  1542. // separator.
  1543. func (m *TableManager) buildIndexValue(row Row, columns []IndexColumn) (string, error) {
  1544. if len(columns) == 1 {
  1545. v, err := m.indexColumnValue(row, columns[0])
  1546. if err != nil {
  1547. return "", err
  1548. }
  1549. return formatIndexValue(v), nil
  1550. }
  1551. parts := make([]string, 0, len(columns))
  1552. for _, col := range columns {
  1553. v, err := m.indexColumnValue(row, col)
  1554. if err != nil {
  1555. return "", err
  1556. }
  1557. parts = append(parts, formatIndexValue(v))
  1558. }
  1559. return strings.Join(parts, "\x00"), nil
  1560. }
  1561. // ── UNIQUE index enforcement ────────────────────────────────────────────────
  1562. //
  1563. // Uniqueness is enforced by scanning durable rows rather than by persisting a
  1564. // separate claim key. There is therefore no storage migration and no new durable
  1565. // state: a table with a UNIQUE index takes its exclusive table gate for writes so
  1566. // a validating scan can never race a concurrent writer. NULL values are exempt
  1567. // (SQLite permits multiple NULLs in a unique index), and composite values are
  1568. // encoded with length prefixes so "a\x00b" in one column can never collide with
  1569. // "a", "b" across two columns.
  1570. // uniqueIndexes returns the UNIQUE indexes defined on a table.
  1571. func (m *TableManager) uniqueIndexes(table string) ([]*Index, error) {
  1572. indexes, err := m.schema.ListTableIndexes(table)
  1573. if err != nil {
  1574. return nil, err
  1575. }
  1576. var uniq []*Index
  1577. for _, idx := range indexes {
  1578. if idx.Unique {
  1579. uniq = append(uniq, idx)
  1580. }
  1581. }
  1582. return uniq, nil
  1583. }
  1584. // hasUniqueIndex reports whether the table has any UNIQUE index. An IO error is
  1585. // surfaced so callers never silently skip uniqueness enforcement.
  1586. func (m *TableManager) hasUniqueIndex(table string) (bool, error) {
  1587. indexes, err := m.uniqueIndexes(table)
  1588. if err != nil {
  1589. return false, err
  1590. }
  1591. return len(indexes) > 0, nil
  1592. }
  1593. // HasUniqueIndex reports whether the table has any UNIQUE index, surfacing IO
  1594. // errors. It is the exported form used by the executor to decide whether to run a
  1595. // DML statement inside an implicit transaction for statement-level atomicity.
  1596. func (m *TableManager) HasUniqueIndex(table string) (bool, error) {
  1597. return m.hasUniqueIndex(table)
  1598. }
  1599. // encodeUniqueValue encodes the indexed value of a row with per-column type tags
  1600. // and length prefixes. It returns isNull=true when any indexed column is NULL, in
  1601. // which case the row is exempt from uniqueness. The length prefix makes composite
  1602. // encodings collision-free. Expression columns are evaluated through the
  1603. // registered evaluator.
  1604. func (m *TableManager) encodeUniqueValue(row Row, columns []IndexColumn) (string, bool, error) {
  1605. var sb strings.Builder
  1606. for _, col := range columns {
  1607. v, err := m.indexColumnValue(row, col)
  1608. if err != nil {
  1609. return "", false, err
  1610. }
  1611. if v == nil {
  1612. return "", true, nil
  1613. }
  1614. s := encodeUniqueScalar(v)
  1615. sb.WriteString(strconv.Itoa(len(s)))
  1616. sb.WriteByte(':')
  1617. sb.WriteString(s)
  1618. }
  1619. return sb.String(), false, nil
  1620. }
  1621. // encodeUniqueScalar encodes a scalar for uniqueness comparison. Integral
  1622. // numerics are canonicalized across their integer/float/unsigned Go
  1623. // representations so a computed value such as 1.5-0.5 (float64) collides with
  1624. // the literal 1 (int64) the same way SQLite's numeric affinity does. Non-integral
  1625. // reals keep a full-precision tag so no distinct value is lost. TEXT and BLOB
  1626. // remain distinct from numbers.
  1627. func encodeUniqueScalar(v interface{}) string {
  1628. switch t := v.(type) {
  1629. case bool:
  1630. if t {
  1631. return "b1"
  1632. }
  1633. return "b0"
  1634. case int:
  1635. return "i" + strconv.FormatInt(int64(t), 10)
  1636. case int64:
  1637. return "i" + strconv.FormatInt(t, 10)
  1638. case uint:
  1639. return "i" + strconv.FormatUint(uint64(t), 10)
  1640. case uint8:
  1641. return "i" + strconv.FormatUint(uint64(t), 10)
  1642. case uint16:
  1643. return "i" + strconv.FormatUint(uint64(t), 10)
  1644. case uint32:
  1645. return "i" + strconv.FormatUint(uint64(t), 10)
  1646. case uint64:
  1647. return "i" + strconv.FormatUint(t, 10)
  1648. case uintptr:
  1649. return "i" + strconv.FormatUint(uint64(t), 10)
  1650. case float64:
  1651. if s, ok := encodeIntegralFloat(t); ok {
  1652. return s
  1653. }
  1654. return "r" + strconv.FormatFloat(t, 'g', -1, 64)
  1655. case string:
  1656. return "s" + t
  1657. case []byte:
  1658. return "x" + string(t)
  1659. default:
  1660. return "s" + fmt.Sprintf("%v", t)
  1661. }
  1662. }
  1663. // encodeIntegralFloat canonicalizes a whole float64 to the same "i" encoding used
  1664. // by integer values, without precision loss, so integral reals and integers are
  1665. // not treated as distinct under a unique index. It reports false (and returns
  1666. // nothing) for non-integral values or values outside the int64 range.
  1667. func encodeIntegralFloat(v float64) (string, bool) {
  1668. if v != math.Trunc(v) {
  1669. return "", false
  1670. }
  1671. if v < -9223372036854775808.0 || v >= 9223372036854775808.0 {
  1672. return "", false
  1673. }
  1674. return "i" + strconv.FormatInt(int64(v), 10), true
  1675. }
  1676. // lockForWrite acquires the table gate appropriate for a point write: exclusive
  1677. // when the table has a UNIQUE index (so the validating scan cannot race another
  1678. // writer), shared otherwise. The uniqueness decision is re-checked under the lock
  1679. // so a concurrent CREATE UNIQUE INDEX cannot slip in between the unlocked probe
  1680. // and the lock acquisition; the returned unlock closes the gate.
  1681. func (m *TableManager) lockForWrite(table string) (unlock func(), unique bool, err error) {
  1682. tl := m.tableLock(table)
  1683. for {
  1684. uniq, err := m.hasUniqueIndex(table)
  1685. if err != nil {
  1686. return nil, false, err
  1687. }
  1688. if uniq {
  1689. tl.Lock()
  1690. // Re-check under the exclusive gate (authoritative): CreateUniqueIndex
  1691. // also takes the exclusive gate, so it cannot run while we hold it.
  1692. uniq, err = m.hasUniqueIndex(table)
  1693. if err != nil {
  1694. tl.Unlock()
  1695. return nil, false, err
  1696. }
  1697. if uniq {
  1698. return tl.Unlock, true, nil
  1699. }
  1700. tl.Unlock()
  1701. continue
  1702. }
  1703. tl.RLock()
  1704. // A unique index could have appeared before we acquired the shared gate;
  1705. // re-check and escalate if so.
  1706. uniq, err = m.hasUniqueIndex(table)
  1707. if err != nil {
  1708. tl.RUnlock()
  1709. return nil, false, err
  1710. }
  1711. if uniq {
  1712. tl.RUnlock()
  1713. continue
  1714. }
  1715. return tl.RUnlock, false, nil
  1716. }
  1717. }
  1718. // ValidateUniqueIndex rejects a UNIQUE index definition if existing rows already
  1719. // contain duplicate non-NULL values for the indexed columns.
  1720. func (m *TableManager) ValidateUniqueIndex(index *Index) error {
  1721. seen := make(map[string]bool)
  1722. return m.scanRows(index.Table, func(row Row) (bool, error) {
  1723. encoded, isNull, err := m.encodeUniqueValue(row, index.Columns)
  1724. if err != nil {
  1725. return true, err
  1726. }
  1727. if isNull {
  1728. return false, nil
  1729. }
  1730. if seen[encoded] {
  1731. return true, &UniqueViolationError{Constraint: index.Name}
  1732. }
  1733. seen[encoded] = true
  1734. return false, nil
  1735. })
  1736. }
  1737. // CreateUniqueIndex validates existing rows and registers the index while
  1738. // holding the table's exclusive gate, so a concurrent writer cannot insert a
  1739. // conflicting value between validation and registration.
  1740. func (m *TableManager) CreateUniqueIndex(index *Index) error {
  1741. tl := m.tableLock(index.Table)
  1742. tl.Lock()
  1743. defer tl.Unlock()
  1744. if err := m.ValidateUniqueIndex(index); err != nil {
  1745. return err
  1746. }
  1747. return m.schema.CreateIndex(index)
  1748. }
  1749. type indexedRowVersion struct {
  1750. row Row
  1751. key string
  1752. lsn uint64
  1753. }
  1754. type indexPredicateSnapshot struct {
  1755. valueKey string
  1756. valueGen uint64
  1757. wildcardKey string
  1758. wildcardGen uint64
  1759. }
  1760. // selectByIndexWithLSN retrieves indexed rows and their durable versions. The
  1761. // transaction layer uses the versions for optimistic commit validation.
  1762. func (m *TableManager) selectByIndexWithLSN(table, indexName string, colValue interface{}) ([]indexedRowVersion, indexPredicateSnapshot, error) {
  1763. return m.selectByIndexKeyWithLSN(table, indexName, formatIndexValue(colValue))
  1764. }
  1765. // IndexRowKey computes the formatted in-memory index key a row maps to for an
  1766. // index. Expression columns are evaluated through the same registered evaluator
  1767. // used by uniqueness enforcement, so the key matches both durable index entries
  1768. // and staged overlay rows.
  1769. func (m *TableManager) IndexRowKey(idx *Index, row Row) (string, error) {
  1770. value, err := m.buildIndexValue(row, idx.Columns)
  1771. if err != nil {
  1772. return "", err
  1773. }
  1774. return formatIndexValue(value), nil
  1775. }
  1776. // IndexValueContainsNull reports whether any column contributing to an index
  1777. // key evaluates to NULL. UNIQUE indexes exempt such rows from conflicts under
  1778. // SQLite semantics.
  1779. func (m *TableManager) IndexValueContainsNull(idx *Index, row Row) (bool, error) {
  1780. _, isNull, err := m.encodeUniqueValue(row, idx.Columns)
  1781. return isNull, err
  1782. }
  1783. // selectByIndexKeyWithLSN is selectByIndexWithLSN with an already-computed
  1784. // formatted index key, so callers can look up composite and expression indexes
  1785. // without re-deriving the key from a single column value.
  1786. func (m *TableManager) selectByIndexKeyWithLSN(table, indexName, valueKey string) ([]indexedRowVersion, indexPredicateSnapshot, error) {
  1787. index, err := m.schema.GetIndex(indexName)
  1788. if err != nil {
  1789. return nil, indexPredicateSnapshot{}, err
  1790. }
  1791. tableKey := strings.ToLower(table)
  1792. tl := m.tableLock(tableKey)
  1793. indexKey := strings.ToLower(indexName)
  1794. for {
  1795. if err := m.ensureIndex(index); err != nil {
  1796. return nil, indexPredicateSnapshot{}, err
  1797. }
  1798. tl.RLock()
  1799. if !m.schema.TableExists(table) {
  1800. tl.RUnlock()
  1801. return nil, indexPredicateSnapshot{}, fmt.Errorf("table not found: %s", table)
  1802. }
  1803. m.cacheMu.RLock()
  1804. if m.disabledIndexes[indexKey] {
  1805. m.cacheMu.RUnlock()
  1806. tl.RUnlock()
  1807. return nil, indexPredicateSnapshot{}, fmt.Errorf("%w: %s is disabled", ErrIndexNotFound, indexName)
  1808. }
  1809. if _, initialized := m.indexCache[indexKey]; initialized {
  1810. break // Keep cacheMu through the complete candidate/key snapshot.
  1811. }
  1812. m.cacheMu.RUnlock()
  1813. tl.RUnlock()
  1814. // Commits can invalidate under a shared table gate. Retry the build,
  1815. // never interpret a missing cache as a legitimately empty index.
  1816. }
  1817. defer tl.RUnlock()
  1818. predicateKey, predicateGen, wildcardKey, wildcardGen := m.predicateSnapshot(table, indexName, valueKey)
  1819. snapshot := indexPredicateSnapshot{
  1820. valueKey: predicateKey, valueGen: predicateGen,
  1821. wildcardKey: wildcardKey, wildcardGen: wildcardGen,
  1822. }
  1823. rowids := append([]int64(nil), m.indexCache[indexKey][valueKey]...)
  1824. primaryKeys := make([]string, 0, len(rowids))
  1825. missingRowID := int64(0)
  1826. missingRowKey := false
  1827. for _, rowid := range rowids {
  1828. if primaryKey, ok := m.rowKeyCache[tableKey][rowid]; ok {
  1829. primaryKeys = append(primaryKeys, primaryKey)
  1830. } else {
  1831. missingRowID = rowid
  1832. missingRowKey = true
  1833. break
  1834. }
  1835. }
  1836. m.cacheMu.RUnlock()
  1837. if missingRowKey {
  1838. return nil, indexPredicateSnapshot{}, fmt.Errorf("index %s is missing rowid %d", indexName, missingRowID)
  1839. }
  1840. // If no rowids found, return empty result
  1841. if len(rowids) == 0 {
  1842. return []indexedRowVersion{}, snapshot, nil
  1843. }
  1844. rows := make([]indexedRowVersion, 0, len(primaryKeys))
  1845. err = m.pool.WithClient(func(client *KVClient) error {
  1846. keys := make([][]byte, len(primaryKeys))
  1847. for i, primaryKey := range primaryKeys {
  1848. keys[i] = []byte(m.dataKey(table, primaryKey))
  1849. }
  1850. results, err := client.MultiGet(keys)
  1851. if err != nil {
  1852. return err
  1853. }
  1854. for i, result := range results {
  1855. if !result.Found {
  1856. primaryKey := primaryKeys[i]
  1857. return fmt.Errorf("index %s references missing primary key %s", indexName, primaryKey)
  1858. }
  1859. row, err := decodeRow(result.Value)
  1860. if err != nil {
  1861. return err
  1862. }
  1863. rows = append(rows, indexedRowVersion{
  1864. row: row,
  1865. key: m.dataKey(table, primaryKeys[i]),
  1866. lsn: result.LSN,
  1867. })
  1868. }
  1869. return nil
  1870. })
  1871. if err != nil {
  1872. return nil, indexPredicateSnapshot{}, err
  1873. }
  1874. return rows, snapshot, nil
  1875. }
  1876. // SelectByIndex retrieves rows using an in-memory equality index followed by a
  1877. // single MultiGet for the matching primary keys.
  1878. func (m *TableManager) SelectByIndex(table, indexName string, colValue interface{}) ([]Row, error) {
  1879. versions, _, err := m.selectByIndexWithLSN(table, indexName, colValue)
  1880. if err != nil {
  1881. return nil, err
  1882. }
  1883. rows := make([]Row, len(versions))
  1884. for i := range versions {
  1885. rows[i] = versions[i].row
  1886. }
  1887. return rows, nil
  1888. }