table.go 56 KB

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