table.go 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964
  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 && col.Default != nil {
  489. normalizedRow[col.Name] = col.Default
  490. }
  491. }
  492. if rowid > 0 {
  493. normalizedRow["_rowid_"] = rowid
  494. } else {
  495. newRowID, err := m.schema.GetNextRowID(table)
  496. if err != nil {
  497. return nil, "", err
  498. }
  499. normalizedRow["_rowid_"] = newRowID
  500. }
  501. if err := m.schema.validateRowConstraints(schema, normalizedRow); err != nil {
  502. return nil, "", err
  503. }
  504. return normalizedRow, m.dataKey(table, pk), nil
  505. }
  506. // Insert inserts a new row. The duplicate check and write are one atomic
  507. // compare-and-swap so concurrent inserts of the same primary key cannot both
  508. // persist. The shared table gate is acquired before the key's striped lock so
  509. // a queued scan writer cannot invert the lock order with point operations.
  510. func (m *TableManager) Insert(table string, row Row) error {
  511. _, err := m.InsertWithRowID(table, row)
  512. return err
  513. }
  514. // InsertWithRowID returns the actual row identifier, never a concurrent counter.
  515. func (m *TableManager) InsertWithRowID(table string, row Row) (int64, error) {
  516. nr, key, err := m.prepareInsert(table, row)
  517. if err != nil {
  518. return 0, err
  519. }
  520. rowid, _ := rowIDFromRow(nr)
  521. wasInit := m.countInitialized(table)
  522. // Point writers share this gate with each other. Transaction commits and
  523. // scan-based writes take it exclusively, so generation validation and cache
  524. // publication are ordered without serializing writes to different keys.
  525. // A UNIQUE index forces the exclusive gate so the validating scan below
  526. // cannot race another writer (or a concurrent CREATE UNIQUE INDEX).
  527. unlock, uniq, err := m.lockForWrite(table)
  528. if err != nil {
  529. return 0, err
  530. }
  531. defer unlock()
  532. // prepareInsert normalized the row before this gate was held, so a
  533. // concurrent ADD COLUMN may have published a column the row image predates.
  534. // Re-apply the schema that is current under the gate; schema DDL needs the
  535. // exclusive form of this gate, so it cannot change again before the write.
  536. schema, err := m.schema.GetSchema(table)
  537. if err != nil {
  538. return 0, err
  539. }
  540. if err := applySchemaDefaults(schema, nr); err != nil {
  541. return 0, err
  542. }
  543. if err := m.schema.validateChecks(schema, nr); err != nil {
  544. return 0, err
  545. }
  546. data, err := encodeRow(nr)
  547. if err != nil {
  548. return 0, fmt.Errorf("failed to serialize row: %w", err)
  549. }
  550. var uniquePlan uniqueCachePlan
  551. if uniq {
  552. uniquePlan, err = m.prepareUniqueRows(table, map[string]*overlayEntry{key: {row: nr}})
  553. if err != nil {
  554. return 0, err
  555. }
  556. }
  557. st := m.stripeKey(key)
  558. st.Lock()
  559. defer st.Unlock()
  560. committed, err := m.compareWritePoint(
  561. []CompareCheck{{Key: []byte(key), LSN: 0}},
  562. []BatchOp{{Op: batchPut, Key: []byte(key), Value: data}},
  563. )
  564. if err != nil {
  565. m.invalidateWriteFailure(table)
  566. return 0, err
  567. }
  568. if !committed {
  569. return 0, &PrimaryKeyViolationError{Table: table, Key: strings.TrimPrefix(key, m.dataPrefix(table))}
  570. }
  571. m.applyUniquePlan(uniquePlan, nil)
  572. if err := m.updateIndexesForRow(table, nr, true, key); err != nil {
  573. return 0, err
  574. }
  575. // Publish derived index state before its generations. A reader that races
  576. // with publication either sees the old generation and aborts or sees the
  577. // complete new state.
  578. if err := m.bumpIndexPredicates(table, nr); err != nil {
  579. return 0, err
  580. }
  581. m.bumpGeneration(table)
  582. m.incrCount(table, schema.CreatedAt, 1, wasInit)
  583. return rowid, nil
  584. }
  585. // bulkBatchByteBudget bounds a single atomic BATCH_WRITE payload below the
  586. // PKBFI frame limit so a bulk insert never emits a frame the server rejects.
  587. // Each op contributes 12 header bytes plus its key and value.
  588. const bulkBatchByteBudget = 60 * 1024 * 1024
  589. // chunkBatchOps splits ops into atomic BATCH_WRITE chunks bounded by both the
  590. // PKBFI operation-count limit and the frame-size limit. Each chunk is a slice
  591. // of the backing array, valid until the next append to ops.
  592. func chunkBatchOps(ops []BatchOp) [][]BatchOp {
  593. var chunks [][]BatchOp
  594. for i := 0; i < len(ops); {
  595. end := i + maxOperations
  596. if end > len(ops) {
  597. end = len(ops)
  598. }
  599. bytes := 0
  600. j := i
  601. for j < end {
  602. sz := 12 + len(ops[j].Key) + len(ops[j].Value)
  603. if j > i && bytes+sz > bulkBatchByteBudget {
  604. break
  605. }
  606. bytes += sz
  607. j++
  608. }
  609. if j == i {
  610. j = i + 1
  611. }
  612. chunks = append(chunks, ops[i:j])
  613. i = j
  614. }
  615. return chunks
  616. }
  617. // InsertBulk inserts multiple rows efficiently using atomic BATCH_WRITE chunks
  618. // bounded by the PKBFI operation-count and frame-size limits. Skips per-row
  619. // duplicate checks (caller must ensure uniqueness). Used by INSERT ... SELECT.
  620. func (m *TableManager) InsertBulk(table string, rows []Row) (int, error) {
  621. count, _, err := m.InsertBulkWithLastRowID(table, rows)
  622. return count, err
  623. }
  624. // InsertBulkWithLastRowID is InsertBulk, additionally returning the ROWID of the
  625. // last persisted row (0 when nothing persisted).
  626. func (m *TableManager) InsertBulkWithLastRowID(table string, rows []Row) (int, int64, error) {
  627. if len(rows) == 0 {
  628. return 0, 0, nil
  629. }
  630. tl := m.tableLock(table)
  631. tl.Lock()
  632. defer tl.Unlock()
  633. schema, err := m.schema.GetSchema(table)
  634. if err != nil {
  635. return 0, 0, err
  636. }
  637. wasInit := m.countInitialized(table)
  638. pkCol, _ := schema.GetColumn(schema.PrimaryKey)
  639. isIntegerPK := pkCol != nil && isIntegerType(pkCol.Type)
  640. // Normalize rows and assign _rowid_.
  641. normalized := make([]Row, 0, len(rows))
  642. var maxRowID int64
  643. for _, row := range rows {
  644. nr := make(Row)
  645. for _, col := range schema.Columns {
  646. for k, v := range row {
  647. if strings.EqualFold(k, col.Name) {
  648. nr[col.Name] = v
  649. break
  650. }
  651. }
  652. }
  653. for _, col := range schema.Columns {
  654. if _, ok := nr[col.Name]; !ok && col.Default != nil {
  655. nr[col.Name] = col.Default
  656. }
  657. }
  658. var rowid int64
  659. var hasRowid bool
  660. if isIntegerPK {
  661. switch v := nr[schema.PrimaryKey].(type) {
  662. case float64:
  663. if math.Trunc(v) != v {
  664. return 0, 0, fmt.Errorf("invalid integer primary key: %v", v)
  665. }
  666. rowid = int64(v)
  667. hasRowid = true
  668. case int64:
  669. rowid = v
  670. hasRowid = true
  671. case int:
  672. rowid = int64(v)
  673. hasRowid = true
  674. }
  675. }
  676. if !hasRowid {
  677. // Auto-generate for an INTEGER primary key or the synthetic _rowid_,
  678. // mirroring prepareInsert so INSERT ... SELECT works on AUTOINCREMENT
  679. // tables.
  680. if isIntegerPK || schema.PrimaryKey == "_rowid_" {
  681. rowid, err = m.schema.GetNextRowID(table)
  682. if err != nil {
  683. return 0, 0, err
  684. }
  685. if isIntegerPK {
  686. nr[schema.PrimaryKey] = rowid
  687. } else {
  688. nr["_rowid_"] = rowid
  689. }
  690. } else {
  691. pk, ok := nr[schema.PrimaryKey]
  692. if !ok || pk == nil {
  693. return 0, 0, fmt.Errorf("missing primary key: %s", schema.PrimaryKey)
  694. }
  695. rowid, err = m.schema.GetNextRowID(table)
  696. if err != nil {
  697. return 0, 0, err
  698. }
  699. }
  700. }
  701. nr["_rowid_"] = rowid
  702. if err := m.schema.validateRowConstraints(schema, nr); err != nil {
  703. return 0, 0, err
  704. }
  705. if rowid > maxRowID {
  706. maxRowID = rowid
  707. }
  708. normalized = append(normalized, nr)
  709. }
  710. if maxRowID > 0 {
  711. m.schema.UpdateMaxRowID(table, maxRowID)
  712. }
  713. // Serialize all rows into batch operations. A parallel slice keeps the
  714. // normalized Row for each op for index maintenance after the write.
  715. ops := make([]BatchOp, 0, len(normalized))
  716. encoded := make([]Row, 0, len(normalized))
  717. for _, nr := range normalized {
  718. pk := fmt.Sprintf("%v", nr[schema.PrimaryKey])
  719. data, err := encodeRow(nr)
  720. if err != nil {
  721. return 0, 0, err
  722. }
  723. ops = append(ops, BatchOp{Op: batchPut, Key: []byte(m.dataKey(table, pk)), Value: data})
  724. encoded = append(encoded, nr)
  725. }
  726. keys := make([][]byte, len(ops))
  727. seen := make(map[string]struct{}, len(ops))
  728. for i, op := range ops {
  729. key := string(op.Key)
  730. if _, duplicate := seen[key]; duplicate {
  731. return 0, 0, &PrimaryKeyViolationError{Table: table, Key: key}
  732. }
  733. seen[key] = struct{}{}
  734. keys[i] = op.Key
  735. }
  736. existing := make([]bool, len(keys))
  737. if err := m.pool.WithClient(func(client *KVClient) error {
  738. for start := 0; start < len(keys); start += maxOperations {
  739. end := start + maxOperations
  740. if end > len(keys) {
  741. end = len(keys)
  742. }
  743. found, err := client.ExistsMany(keys[start:end])
  744. if err != nil {
  745. return err
  746. }
  747. copy(existing[start:end], found)
  748. }
  749. return nil
  750. }); err != nil {
  751. return 0, 0, err
  752. }
  753. for i, found := range existing {
  754. if found {
  755. return 0, 0, &PrimaryKeyViolationError{Table: table, Key: string(ops[i].Key)}
  756. }
  757. }
  758. var uniquePlan uniqueCachePlan
  759. unique, err := m.hasUniqueIndex(table)
  760. if err != nil {
  761. return 0, 0, err
  762. }
  763. if unique {
  764. uniqueEntries := make(map[string]*overlayEntry, len(encoded))
  765. for i, row := range encoded {
  766. uniqueEntries[string(ops[i].Key)] = &overlayEntry{row: row}
  767. }
  768. uniquePlan, err = m.prepareUniqueRows(table, uniqueEntries)
  769. if err != nil {
  770. return 0, 0, err
  771. }
  772. }
  773. // Write rows in atomic BATCH_WRITE chunks. Maintain in-memory indexes only
  774. // for rows that actually persisted, so a partial failure cannot leave an
  775. // already-built index stale.
  776. var firstErr error
  777. numOK := 0
  778. for _, chunk := range chunkBatchOps(ops) {
  779. err := m.pool.WithClient(func(c *KVClient) error {
  780. _, err := c.BatchWrite(chunk, nil)
  781. return err
  782. })
  783. if err != nil {
  784. if firstErr == nil {
  785. firstErr = err
  786. }
  787. break
  788. }
  789. numOK += len(chunk)
  790. }
  791. // Maintain indexes for the rows that persisted (the first numOK ops).
  792. if len(uniquePlan) != 0 {
  793. accepted := make(map[string]bool, numOK)
  794. for i := 0; i < numOK; i++ {
  795. accepted[string(ops[i].Key)] = true
  796. }
  797. m.applyUniquePlan(uniquePlan, accepted)
  798. }
  799. for i := 0; i < numOK; i++ {
  800. if err := m.updateIndexesForRow(table, encoded[i], true, string(ops[i].Key)); err != nil {
  801. return numOK, 0, err
  802. }
  803. }
  804. if numOK > 0 {
  805. m.bumpGeneration(table)
  806. if err := m.bumpIndexPredicates(table, encoded[:numOK]...); err != nil {
  807. return numOK, 0, err
  808. }
  809. }
  810. m.incrCount(table, schema.CreatedAt, numOK, wasInit)
  811. if firstErr != nil {
  812. m.invalidateWriteFailure(table)
  813. }
  814. var lastRowID int64
  815. if numOK > 0 {
  816. lastRowID, _ = rowIDFromRow(encoded[numOK-1])
  817. }
  818. return numOK, lastRowID, firstErr
  819. }
  820. // updateIndexesForRow adds or removes entries from already-built in-memory
  821. // indexes. Index entries are rebuildable from durable row data, so this method
  822. // intentionally does not write idx:* keys to KV.
  823. func (m *TableManager) updateIndexesForRow(table string, row Row, add bool, actualKey string) error {
  824. indexes, err := m.schema.ListTableIndexes(table)
  825. if err != nil || len(indexes) == 0 {
  826. return err
  827. }
  828. rowid, ok := rowIDFromRow(row)
  829. if !ok {
  830. return nil
  831. }
  832. tableKey := strings.ToLower(table)
  833. m.cacheMu.Lock()
  834. if keys, initialized := m.rowKeyCache[tableKey]; initialized {
  835. pk := strings.TrimPrefix(actualKey, m.dataPrefix(table))
  836. reverse := m.keyRowCache[tableKey]
  837. if add {
  838. keys[rowid] = pk
  839. reverse[pk] = rowid
  840. } else {
  841. delete(keys, rowid)
  842. delete(reverse, pk)
  843. }
  844. }
  845. m.cacheMu.Unlock()
  846. for _, idx := range indexes {
  847. indexName := strings.ToLower(idx.Name)
  848. m.cacheMu.RLock()
  849. _, initialized := m.indexCache[indexName]
  850. m.cacheMu.RUnlock()
  851. if !initialized {
  852. continue
  853. }
  854. colValue, err := m.buildIndexValue(row, idx.Columns)
  855. if err != nil {
  856. return err
  857. }
  858. if add {
  859. m.AddIndexEntry(idx.Name, colValue, rowid)
  860. } else {
  861. m.RemoveIndexEntry(idx.Name, colValue, rowid)
  862. }
  863. }
  864. return nil
  865. }
  866. // Select retrieves rows from a table by scanning durable rows and collecting
  867. // only matching rows.
  868. func (m *TableManager) Select(table string, filter func(Row) bool) ([]Row, error) {
  869. tl := m.tableLock(table)
  870. tl.RLock()
  871. defer tl.RUnlock()
  872. return m.selectRows(table, filter)
  873. }
  874. // selectRows scans a table while the caller holds its shared or exclusive gate.
  875. func (m *TableManager) selectRows(table string, filter func(Row) bool) ([]Row, error) {
  876. if !m.schema.TableExists(table) {
  877. return nil, fmt.Errorf("table not found: %s", table)
  878. }
  879. rows := make([]Row, 0)
  880. err := m.scanRows(table, func(row Row) (bool, error) {
  881. if filter == nil || filter(row) {
  882. rows = append(rows, row)
  883. }
  884. return false, nil
  885. })
  886. if err != nil {
  887. return nil, err
  888. }
  889. return rows, nil
  890. }
  891. func cloneRow(row Row) Row {
  892. if row == nil {
  893. return nil
  894. }
  895. cloned := make(Row, len(row))
  896. for k, v := range row {
  897. cloned[k] = v
  898. }
  899. return cloned
  900. }
  901. // SelectWithLimit retrieves rows with limit and offset, applying filter/offset
  902. // while scanning and closing the scan early once the limit is reached.
  903. func (m *TableManager) SelectWithLimit(table string, filter func(Row) bool, limit, offset int) ([]Row, error) {
  904. tl := m.tableLock(table)
  905. tl.RLock()
  906. defer tl.RUnlock()
  907. if !m.schema.TableExists(table) {
  908. return nil, fmt.Errorf("table not found: %s", table)
  909. }
  910. rows := make([]Row, 0)
  911. skipped := 0
  912. pageSize := scanPageSize
  913. if limit > 0 {
  914. desired := limit
  915. if offset > 0 {
  916. if offset >= scanPageSize-desired {
  917. desired = scanPageSize
  918. } else {
  919. desired += offset
  920. }
  921. }
  922. if desired < 1 {
  923. desired = 1
  924. }
  925. if desired < pageSize {
  926. pageSize = desired
  927. }
  928. }
  929. err := m.scanRowsWithPageSize(table, uint32(pageSize), func(row Row) (bool, error) {
  930. if filter != nil && !filter(row) {
  931. return false, nil
  932. }
  933. if skipped < offset {
  934. skipped++
  935. return false, nil
  936. }
  937. rows = append(rows, row)
  938. return limit > 0 && len(rows) >= limit, nil
  939. })
  940. if err != nil {
  941. return nil, err
  942. }
  943. return rows, nil
  944. }
  945. // Update updates rows matching the filter.
  946. func (m *TableManager) Update(table string, updates Row, filter func(Row) bool) (int, error) {
  947. return m.updateLocked(table, func(Row) (Row, error) { return updates, nil }, filter)
  948. }
  949. // UpdateFunc updates rows matching the filter using a function to compute new values.
  950. // The updateFn receives the current row and returns the updates to apply.
  951. func (m *TableManager) UpdateFunc(table string, updateFn func(Row) (Row, error), filter func(Row) bool) (int, error) {
  952. return m.updateLocked(table, updateFn, filter)
  953. }
  954. // updateLocked stages the complete update before one compare-batch publication.
  955. // Evaluation, encoding, validation or I/O errors must never leave earlier rows
  956. // committed, including when a primary key moves to a different durable key.
  957. func (m *TableManager) updateLocked(table string, updateFn func(Row) (Row, error), filter func(Row) bool) (int, error) {
  958. session := NewSession(m.schema, m)
  959. if err := session.Begin(); err != nil {
  960. return 0, err
  961. }
  962. defer session.Rollback()
  963. count, err := session.UpdateFunc(table, updateFn, filter)
  964. if err != nil {
  965. return 0, err
  966. }
  967. if err := session.Commit(); err != nil {
  968. return 0, err
  969. }
  970. return count, nil
  971. }
  972. // UpdateByPK updates one row without scanning the table. It uses the key's
  973. // striped lock and a compare-and-swap write so a concurrent modification of the
  974. // same row fails with a serialization error instead of being silently lost.
  975. func (m *TableManager) UpdateByPK(table, pk string, updateFn func(Row) (Row, error)) (Row, bool, error) {
  976. key := m.dataKey(table, pk)
  977. unlock, uniq, err := m.lockForWrite(table)
  978. if err != nil {
  979. return nil, false, err
  980. }
  981. defer unlock()
  982. // Read the schema under the gate so validation sees every column a
  983. // concurrent ADD COLUMN has published; the row itself is read below, also
  984. // under the gate.
  985. schema, err := m.schema.GetSchema(table)
  986. if err != nil {
  987. return nil, false, err
  988. }
  989. st := m.stripeKey(key)
  990. st.Lock()
  991. defer st.Unlock()
  992. row, lsn, err := m.getByPKWithLSN(table, pk)
  993. if err == ErrKeyNotFound {
  994. return nil, false, nil
  995. }
  996. if err != nil {
  997. return nil, false, err
  998. }
  999. oldRow := cloneRow(row)
  1000. updates, err := updateFn(row)
  1001. if err != nil {
  1002. return nil, false, err
  1003. }
  1004. for name, value := range updates {
  1005. for _, column := range schema.Columns {
  1006. if strings.EqualFold(name, column.Name) {
  1007. row[column.Name] = value
  1008. break
  1009. }
  1010. }
  1011. }
  1012. if err := applySchemaDefaults(schema, row); err != nil {
  1013. return nil, false, err
  1014. }
  1015. if err := m.schema.validateChecks(schema, row); err != nil {
  1016. return nil, false, err
  1017. }
  1018. data, err := encodeRow(row)
  1019. if err != nil {
  1020. return nil, false, err
  1021. }
  1022. var uniquePlan uniqueCachePlan
  1023. if uniq {
  1024. uniquePlan, err = m.prepareUniqueRows(table, map[string]*overlayEntry{key: {row: row}})
  1025. if err != nil {
  1026. return nil, false, err
  1027. }
  1028. }
  1029. committed, err := m.compareWritePoint(
  1030. []CompareCheck{{Key: []byte(key), LSN: lsn}},
  1031. []BatchOp{{Op: batchPut, Key: []byte(key), Value: data}},
  1032. )
  1033. if err != nil {
  1034. m.invalidateWriteFailure(table)
  1035. return nil, false, err
  1036. }
  1037. if !committed {
  1038. return nil, false, ErrSerialization
  1039. }
  1040. m.applyUniquePlan(uniquePlan, nil)
  1041. if err := m.updateIndexesForRow(table, oldRow, false, key); err != nil {
  1042. return nil, false, err
  1043. }
  1044. if err := m.updateIndexesForRow(table, row, true, key); err != nil {
  1045. return nil, false, err
  1046. }
  1047. if err := m.bumpIndexPredicates(table, oldRow, row); err != nil {
  1048. return nil, false, err
  1049. }
  1050. m.bumpGeneration(table)
  1051. return oldRow, true, nil
  1052. }
  1053. // Delete deletes rows matching the filter.
  1054. func (m *TableManager) Delete(table string, filter func(Row) bool) (int, error) {
  1055. session := NewSession(m.schema, m)
  1056. if err := session.Begin(); err != nil {
  1057. return 0, err
  1058. }
  1059. defer session.Rollback()
  1060. count, err := session.Delete(table, filter)
  1061. if err != nil {
  1062. return 0, err
  1063. }
  1064. if err := session.Commit(); err != nil {
  1065. return 0, err
  1066. }
  1067. return count, nil
  1068. }
  1069. // DeleteByPK deletes one row without scanning the table, using the key's
  1070. // striped lock and a compare-and-swap delete.
  1071. func (m *TableManager) DeleteByPK(table, pk string) (Row, bool, error) {
  1072. schema, err := m.schema.GetSchema(table)
  1073. if err != nil {
  1074. return nil, false, err
  1075. }
  1076. key := m.dataKey(table, pk)
  1077. tl := m.tableLock(table)
  1078. tl.RLock()
  1079. defer tl.RUnlock()
  1080. st := m.stripeKey(key)
  1081. st.Lock()
  1082. defer st.Unlock()
  1083. wasInit := m.countInitialized(table)
  1084. row, lsn, err := m.getByPKWithLSN(table, pk)
  1085. if err == ErrKeyNotFound {
  1086. return nil, false, nil
  1087. }
  1088. if err != nil {
  1089. return nil, false, err
  1090. }
  1091. committed, err := m.compareWritePoint(
  1092. []CompareCheck{{Key: []byte(key), LSN: lsn}},
  1093. []BatchOp{{Op: batchDelete, Key: []byte(key)}},
  1094. )
  1095. if err != nil {
  1096. m.invalidateWriteFailure(table)
  1097. return nil, false, err
  1098. }
  1099. if !committed {
  1100. return nil, false, ErrSerialization
  1101. }
  1102. m.removeUniqueKey(table, key)
  1103. if err := m.updateIndexesForRow(table, row, false, key); err != nil {
  1104. return nil, false, err
  1105. }
  1106. if err := m.bumpIndexPredicates(table, row); err != nil {
  1107. return nil, false, err
  1108. }
  1109. m.bumpGeneration(table)
  1110. m.incrCount(table, schema.CreatedAt, -1, wasInit)
  1111. return row, true, nil
  1112. }
  1113. // GetByPK retrieves a row by primary key. Point reads take only the key's
  1114. // striped lock so reads of different keys progress concurrently.
  1115. func (m *TableManager) GetByPK(table string, pk string) (Row, error) {
  1116. key := m.dataKey(table, pk)
  1117. st := m.stripeKey(key)
  1118. st.Lock()
  1119. defer st.Unlock()
  1120. if !m.schema.TableExists(table) {
  1121. return nil, fmt.Errorf("table not found: %s", table)
  1122. }
  1123. row, _, err := m.getByPKWithLSN(table, pk)
  1124. return row, err
  1125. }
  1126. // getByPKWithLSN reads a row by primary key and returns its KV LSN (0 when
  1127. // absent). It performs no locking; callers must hold the appropriate striped
  1128. // or table lock.
  1129. func (m *TableManager) getByPKWithLSN(table, pk string) (Row, uint64, error) {
  1130. key := m.dataKey(table, pk)
  1131. var value []byte
  1132. var lsn uint64
  1133. err := m.pool.WithClient(func(c *KVClient) error {
  1134. res, err := c.Get([]byte(key))
  1135. if err != nil {
  1136. return err
  1137. }
  1138. value = res.Value
  1139. lsn = res.LSN
  1140. return nil
  1141. })
  1142. if err != nil {
  1143. if err == ErrKeyNotFound {
  1144. return nil, 0, ErrKeyNotFound
  1145. }
  1146. return nil, 0, err
  1147. }
  1148. row, err := decodeRow(value)
  1149. if err != nil {
  1150. return nil, 0, fmt.Errorf("failed to parse row: %w", err)
  1151. }
  1152. return row, lsn, nil
  1153. }
  1154. // Count returns the number of rows in a table matching the filter.
  1155. func (m *TableManager) Count(table string, filter func(Row) bool) (int, error) {
  1156. tl := m.tableLock(table)
  1157. tl.RLock()
  1158. defer tl.RUnlock()
  1159. if !m.schema.TableExists(table) {
  1160. return 0, fmt.Errorf("table not found: %s", table)
  1161. }
  1162. count := 0
  1163. err := m.scanRows(table, func(row Row) (bool, error) {
  1164. if filter == nil || filter(row) {
  1165. count++
  1166. }
  1167. return false, nil
  1168. })
  1169. if err != nil {
  1170. return 0, err
  1171. }
  1172. return count, nil
  1173. }
  1174. // Truncate removes all rows from a table.
  1175. func (m *TableManager) Truncate(table string) (int, error) {
  1176. return m.Delete(table, nil)
  1177. }
  1178. // isIntegerType checks if a type name is an integer type.
  1179. func isIntegerType(typeName string) bool {
  1180. t := strings.ToUpper(typeName)
  1181. switch t {
  1182. case "INTEGER", "INT", "SMALLINT", "BIGINT", "TINYINT", "MEDIUMINT":
  1183. return true
  1184. }
  1185. return false
  1186. }
  1187. // IsRowIDColumn checks if a column name is a ROWID alias.
  1188. func IsRowIDColumn(name string) bool {
  1189. n := strings.ToLower(name)
  1190. return n == "rowid" || n == "oid" || n == "_rowid_"
  1191. }
  1192. // Index entry methods - leveraging radix trie for prefix-based lookups
  1193. // Format: {database}:idx:{index_name}:{column_value} → JSON array of rowids
  1194. // indexEntryKey returns the key for an index entry.
  1195. func (m *TableManager) indexEntryKey(indexName string, colValue interface{}) string {
  1196. return fmt.Sprintf("%s:idx:%s:%s", m.database, strings.ToLower(indexName), formatIndexValue(colValue))
  1197. }
  1198. // indexPrefix returns the prefix for all entries of an index.
  1199. func (m *TableManager) indexPrefix(indexName string) string {
  1200. return fmt.Sprintf("%s:idx:%s:", m.database, strings.ToLower(indexName))
  1201. }
  1202. func formatIndexValue(value interface{}) string {
  1203. // Equality predicates compare numeric values (including numeric text) as
  1204. // float64. Use the same equivalence classes without decimal rounding.
  1205. // Index hits are candidates: the executor still evaluates the predicate.
  1206. var number float64
  1207. switch v := value.(type) {
  1208. case float64:
  1209. number = v
  1210. case int64:
  1211. number = float64(v)
  1212. case int:
  1213. number = float64(v)
  1214. case bool:
  1215. if v {
  1216. return "1"
  1217. }
  1218. return "0"
  1219. case []byte:
  1220. return formatIndexValue(string(v))
  1221. case string:
  1222. parsed, err := strconv.ParseFloat(v, 64)
  1223. if err != nil {
  1224. return v
  1225. }
  1226. number = parsed
  1227. default:
  1228. return fmt.Sprintf("%v", v)
  1229. }
  1230. if number == 0 {
  1231. return "0"
  1232. }
  1233. return strconv.FormatFloat(number, 'g', -1, 64)
  1234. }
  1235. func rowIDFromRow(row Row) (int64, bool) {
  1236. switch v := row["_rowid_"].(type) {
  1237. case int64:
  1238. return v, true
  1239. case int:
  1240. return int64(v), true
  1241. case float64:
  1242. return int64(v), true
  1243. default:
  1244. return 0, false
  1245. }
  1246. }
  1247. func (m *TableManager) ensureIndex(index *Index) error {
  1248. indexKey := strings.ToLower(index.Name)
  1249. m.cacheMu.RLock()
  1250. disabled := m.disabledIndexes[indexKey]
  1251. _, initialized := m.indexCache[indexKey]
  1252. m.cacheMu.RUnlock()
  1253. if disabled {
  1254. return nil
  1255. }
  1256. if initialized {
  1257. return nil
  1258. }
  1259. // Serialize index build against writes to the same table so the derived
  1260. // entries cannot miss a concurrently-inserted row.
  1261. table := index.Table
  1262. key := strings.ToLower(table)
  1263. tl := m.tableLock(key)
  1264. tl.Lock()
  1265. defer tl.Unlock()
  1266. m.cacheMu.RLock()
  1267. disabled = m.disabledIndexes[indexKey]
  1268. _, initialized = m.indexCache[indexKey]
  1269. m.cacheMu.RUnlock()
  1270. if disabled {
  1271. return nil
  1272. }
  1273. if initialized {
  1274. return nil
  1275. }
  1276. tableSchema, err := m.schema.GetSchema(table)
  1277. if err != nil {
  1278. return err
  1279. }
  1280. values := make(map[string][]int64)
  1281. rowKeys := make(map[int64]string)
  1282. if err := m.scanRows(table, func(row Row) (bool, error) {
  1283. rowid, ok := rowIDFromRow(row)
  1284. if !ok {
  1285. return false, nil
  1286. }
  1287. colValue, err := m.buildIndexValue(row, index.Columns)
  1288. if err != nil {
  1289. return true, err
  1290. }
  1291. valueKey := formatIndexValue(colValue)
  1292. values[valueKey] = append(values[valueKey], rowid)
  1293. rowKeys[rowid] = fmt.Sprintf("%v", row[tableSchema.PrimaryKey])
  1294. return false, nil
  1295. }); err != nil {
  1296. return err
  1297. }
  1298. m.cacheMu.Lock()
  1299. if _, initialized := m.indexCache[indexKey]; !initialized {
  1300. m.installIndexCacheLocked(indexKey, key, values, rowKeys)
  1301. }
  1302. m.cacheMu.Unlock()
  1303. return nil
  1304. }
  1305. // AddIndexEntry adds a rowid to an in-memory index entry.
  1306. func (m *TableManager) AddIndexEntry(indexName string, colValue interface{}, rowid int64) error {
  1307. indexKey := strings.ToLower(indexName)
  1308. valueKey := formatIndexValue(colValue)
  1309. m.cacheMu.Lock()
  1310. defer m.cacheMu.Unlock()
  1311. values, ok := m.indexCache[indexKey]
  1312. if !ok {
  1313. return nil
  1314. }
  1315. rowids := values[valueKey]
  1316. for _, r := range rowids {
  1317. if r == rowid {
  1318. return nil
  1319. }
  1320. }
  1321. values[valueKey] = append(rowids, rowid)
  1322. if m.indexRowValues[indexKey] == nil {
  1323. m.indexRowValues[indexKey] = make(map[int64]string)
  1324. }
  1325. m.indexRowValues[indexKey][rowid] = valueKey
  1326. return nil
  1327. }
  1328. // RemoveIndexEntry removes a rowid from an in-memory index entry.
  1329. func (m *TableManager) RemoveIndexEntry(indexName string, colValue interface{}, rowid int64) error {
  1330. indexKey := strings.ToLower(indexName)
  1331. valueKey := formatIndexValue(colValue)
  1332. m.cacheMu.Lock()
  1333. defer m.cacheMu.Unlock()
  1334. m.removeIndexEntryLocked(indexKey, valueKey, rowid)
  1335. return nil
  1336. }
  1337. // LookupIndex returns rowids matching a column value using the index.
  1338. func (m *TableManager) LookupIndex(indexName string, colValue interface{}) ([]int64, error) {
  1339. index, err := m.schema.GetIndex(indexName)
  1340. if err != nil {
  1341. return nil, err
  1342. }
  1343. indexKey := strings.ToLower(indexName)
  1344. valueKey := formatIndexValue(colValue)
  1345. for {
  1346. if err := m.ensureIndex(index); err != nil {
  1347. return nil, err
  1348. }
  1349. m.cacheMu.RLock()
  1350. values, initialized := m.indexCache[indexKey]
  1351. disabled := m.disabledIndexes[indexKey]
  1352. rowids := append([]int64(nil), values[valueKey]...)
  1353. m.cacheMu.RUnlock()
  1354. if disabled {
  1355. return nil, fmt.Errorf("%w: %s is disabled", ErrIndexNotFound, indexName)
  1356. }
  1357. if initialized {
  1358. return rowids, nil
  1359. }
  1360. // A shared-gate commit invalidated the cache after ensureIndex.
  1361. }
  1362. }
  1363. // ClearIndex removes an index's in-memory entries and marks it disabled so a
  1364. // concurrent lookup cannot rebuild it after DROP but before the schema entry
  1365. // is removed. Index entries are derived from durable rows, so there is nothing
  1366. // durable to delete here.
  1367. func (m *TableManager) ClearIndex(indexName, tableName string, columns []string) error {
  1368. indexKey := strings.ToLower(indexName)
  1369. tableKey := strings.ToLower(tableName)
  1370. m.cacheMu.Lock()
  1371. delete(m.indexCache, indexKey)
  1372. delete(m.indexRowValues, indexKey)
  1373. delete(m.indexTable, indexKey)
  1374. delete(m.uniqueCache, indexKey)
  1375. m.disabledIndexes[indexKey] = true
  1376. rowKeysNeeded := false
  1377. for _, indexedTable := range m.indexTable {
  1378. if indexedTable == tableKey {
  1379. rowKeysNeeded = true
  1380. break
  1381. }
  1382. }
  1383. if !rowKeysNeeded {
  1384. delete(m.rowKeyCache, tableKey)
  1385. delete(m.keyRowCache, tableKey)
  1386. }
  1387. m.cacheMu.Unlock()
  1388. return nil
  1389. }
  1390. // BuildIndex builds index entries for all existing rows in a table.
  1391. func (m *TableManager) BuildIndex(indexName, tableName string, columns []string) error {
  1392. indexKey := strings.ToLower(indexName)
  1393. m.cacheMu.Lock()
  1394. delete(m.disabledIndexes, indexKey)
  1395. delete(m.indexCache, indexKey)
  1396. delete(m.indexRowValues, indexKey)
  1397. delete(m.indexTable, indexKey)
  1398. m.cacheMu.Unlock()
  1399. index, err := m.schema.GetIndex(indexName)
  1400. if err == nil {
  1401. return m.ensureIndex(index)
  1402. }
  1403. if !errors.Is(err, ErrIndexNotFound) {
  1404. return err
  1405. }
  1406. tableSchema, schemaErr := m.schema.GetSchema(tableName)
  1407. if schemaErr != nil {
  1408. return schemaErr
  1409. }
  1410. indexCols := make([]IndexColumn, len(columns))
  1411. for i, name := range columns {
  1412. indexCols[i] = IndexColumn{Name: name}
  1413. }
  1414. values := make(map[string][]int64)
  1415. rowKeys := make(map[int64]string)
  1416. if err := m.scanRows(tableName, func(row Row) (bool, error) {
  1417. rowid, ok := rowIDFromRow(row)
  1418. if !ok {
  1419. return false, nil
  1420. }
  1421. colValue, err := m.buildIndexValue(row, indexCols)
  1422. if err != nil {
  1423. return true, err
  1424. }
  1425. values[formatIndexValue(colValue)] = append(values[formatIndexValue(colValue)], rowid)
  1426. rowKeys[rowid] = fmt.Sprintf("%v", row[tableSchema.PrimaryKey])
  1427. return false, nil
  1428. }); err != nil {
  1429. return err
  1430. }
  1431. m.cacheMu.Lock()
  1432. m.installIndexCacheLocked(indexKey, strings.ToLower(tableName), values, rowKeys)
  1433. m.cacheMu.Unlock()
  1434. return nil
  1435. }
  1436. // indexColumnValue resolves a single index column's value for a row. A plain
  1437. // column is looked up case-insensitively; an expression column is evaluated
  1438. // through the registered expression evaluator.
  1439. func (m *TableManager) indexColumnValue(row Row, col IndexColumn) (interface{}, error) {
  1440. if col.Expression != "" {
  1441. eval := m.expressionEvaluator()
  1442. if eval == nil {
  1443. return nil, fmt.Errorf("expression index column %q requires an expression evaluator", col.Expression)
  1444. }
  1445. return eval(col.Expression, row)
  1446. }
  1447. if v, ok := row[col.Name]; ok {
  1448. return v, nil
  1449. }
  1450. for k, v := range row {
  1451. if strings.EqualFold(k, col.Name) {
  1452. return v, nil
  1453. }
  1454. }
  1455. return nil, nil
  1456. }
  1457. // buildIndexValue creates the index key value from an index's columns. Single
  1458. // column values are formatted directly; composite values are joined with a NUL
  1459. // separator.
  1460. func (m *TableManager) buildIndexValue(row Row, columns []IndexColumn) (string, error) {
  1461. if len(columns) == 1 {
  1462. v, err := m.indexColumnValue(row, columns[0])
  1463. if err != nil {
  1464. return "", err
  1465. }
  1466. return formatIndexValue(v), nil
  1467. }
  1468. parts := make([]string, 0, len(columns))
  1469. for _, col := range columns {
  1470. v, err := m.indexColumnValue(row, col)
  1471. if err != nil {
  1472. return "", err
  1473. }
  1474. parts = append(parts, formatIndexValue(v))
  1475. }
  1476. return strings.Join(parts, "\x00"), nil
  1477. }
  1478. // ── UNIQUE index enforcement ────────────────────────────────────────────────
  1479. //
  1480. // Uniqueness is enforced by scanning durable rows rather than by persisting a
  1481. // separate claim key. There is therefore no storage migration and no new durable
  1482. // state: a table with a UNIQUE index takes its exclusive table gate for writes so
  1483. // a validating scan can never race a concurrent writer. NULL values are exempt
  1484. // (SQLite permits multiple NULLs in a unique index), and composite values are
  1485. // encoded with length prefixes so "a\x00b" in one column can never collide with
  1486. // "a", "b" across two columns.
  1487. // uniqueIndexes returns the UNIQUE indexes defined on a table.
  1488. func (m *TableManager) uniqueIndexes(table string) ([]*Index, error) {
  1489. indexes, err := m.schema.ListTableIndexes(table)
  1490. if err != nil {
  1491. return nil, err
  1492. }
  1493. var uniq []*Index
  1494. for _, idx := range indexes {
  1495. if idx.Unique {
  1496. uniq = append(uniq, idx)
  1497. }
  1498. }
  1499. return uniq, nil
  1500. }
  1501. // hasUniqueIndex reports whether the table has any UNIQUE index. An IO error is
  1502. // surfaced so callers never silently skip uniqueness enforcement.
  1503. func (m *TableManager) hasUniqueIndex(table string) (bool, error) {
  1504. indexes, err := m.uniqueIndexes(table)
  1505. if err != nil {
  1506. return false, err
  1507. }
  1508. return len(indexes) > 0, nil
  1509. }
  1510. // HasUniqueIndex reports whether the table has any UNIQUE index, surfacing IO
  1511. // errors. It is the exported form used by the executor to decide whether to run a
  1512. // DML statement inside an implicit transaction for statement-level atomicity.
  1513. func (m *TableManager) HasUniqueIndex(table string) (bool, error) {
  1514. return m.hasUniqueIndex(table)
  1515. }
  1516. // encodeUniqueValue encodes the indexed value of a row with per-column type tags
  1517. // and length prefixes. It returns isNull=true when any indexed column is NULL, in
  1518. // which case the row is exempt from uniqueness. The length prefix makes composite
  1519. // encodings collision-free. Expression columns are evaluated through the
  1520. // registered evaluator.
  1521. func (m *TableManager) encodeUniqueValue(row Row, columns []IndexColumn) (string, bool, error) {
  1522. var sb strings.Builder
  1523. for _, col := range columns {
  1524. v, err := m.indexColumnValue(row, col)
  1525. if err != nil {
  1526. return "", false, err
  1527. }
  1528. if v == nil {
  1529. return "", true, nil
  1530. }
  1531. s := encodeUniqueScalar(v)
  1532. sb.WriteString(strconv.Itoa(len(s)))
  1533. sb.WriteByte(':')
  1534. sb.WriteString(s)
  1535. }
  1536. return sb.String(), false, nil
  1537. }
  1538. // encodeUniqueScalar encodes a scalar for uniqueness comparison. Integral
  1539. // numerics are canonicalized across their integer/float/unsigned Go
  1540. // representations so a computed value such as 1.5-0.5 (float64) collides with
  1541. // the literal 1 (int64) the same way SQLite's numeric affinity does. Non-integral
  1542. // reals keep a full-precision tag so no distinct value is lost. TEXT and BLOB
  1543. // remain distinct from numbers.
  1544. func encodeUniqueScalar(v interface{}) string {
  1545. switch t := v.(type) {
  1546. case bool:
  1547. if t {
  1548. return "b1"
  1549. }
  1550. return "b0"
  1551. case int:
  1552. return "i" + strconv.FormatInt(int64(t), 10)
  1553. case int64:
  1554. return "i" + strconv.FormatInt(t, 10)
  1555. case uint:
  1556. return "i" + strconv.FormatUint(uint64(t), 10)
  1557. case uint8:
  1558. return "i" + strconv.FormatUint(uint64(t), 10)
  1559. case uint16:
  1560. return "i" + strconv.FormatUint(uint64(t), 10)
  1561. case uint32:
  1562. return "i" + strconv.FormatUint(uint64(t), 10)
  1563. case uint64:
  1564. return "i" + strconv.FormatUint(t, 10)
  1565. case uintptr:
  1566. return "i" + strconv.FormatUint(uint64(t), 10)
  1567. case float64:
  1568. if s, ok := encodeIntegralFloat(t); ok {
  1569. return s
  1570. }
  1571. return "r" + strconv.FormatFloat(t, 'g', -1, 64)
  1572. case string:
  1573. return "s" + t
  1574. case []byte:
  1575. return "x" + string(t)
  1576. default:
  1577. return "s" + fmt.Sprintf("%v", t)
  1578. }
  1579. }
  1580. // encodeIntegralFloat canonicalizes a whole float64 to the same "i" encoding used
  1581. // by integer values, without precision loss, so integral reals and integers are
  1582. // not treated as distinct under a unique index. It reports false (and returns
  1583. // nothing) for non-integral values or values outside the int64 range.
  1584. func encodeIntegralFloat(v float64) (string, bool) {
  1585. if v != math.Trunc(v) {
  1586. return "", false
  1587. }
  1588. if v < -9223372036854775808.0 || v >= 9223372036854775808.0 {
  1589. return "", false
  1590. }
  1591. return "i" + strconv.FormatInt(int64(v), 10), true
  1592. }
  1593. // lockForWrite acquires the table gate appropriate for a point write: exclusive
  1594. // when the table has a UNIQUE index (so the validating scan cannot race another
  1595. // writer), shared otherwise. The uniqueness decision is re-checked under the lock
  1596. // so a concurrent CREATE UNIQUE INDEX cannot slip in between the unlocked probe
  1597. // and the lock acquisition; the returned unlock closes the gate.
  1598. func (m *TableManager) lockForWrite(table string) (unlock func(), unique bool, err error) {
  1599. tl := m.tableLock(table)
  1600. for {
  1601. uniq, err := m.hasUniqueIndex(table)
  1602. if err != nil {
  1603. return nil, false, err
  1604. }
  1605. if uniq {
  1606. tl.Lock()
  1607. // Re-check under the exclusive gate (authoritative): CreateUniqueIndex
  1608. // also takes the exclusive gate, so it cannot run while we hold it.
  1609. uniq, err = m.hasUniqueIndex(table)
  1610. if err != nil {
  1611. tl.Unlock()
  1612. return nil, false, err
  1613. }
  1614. if uniq {
  1615. return tl.Unlock, true, nil
  1616. }
  1617. tl.Unlock()
  1618. continue
  1619. }
  1620. tl.RLock()
  1621. // A unique index could have appeared before we acquired the shared gate;
  1622. // re-check and escalate if so.
  1623. uniq, err = m.hasUniqueIndex(table)
  1624. if err != nil {
  1625. tl.RUnlock()
  1626. return nil, false, err
  1627. }
  1628. if uniq {
  1629. tl.RUnlock()
  1630. continue
  1631. }
  1632. return tl.RUnlock, false, nil
  1633. }
  1634. }
  1635. // ValidateUniqueIndex rejects a UNIQUE index definition if existing rows already
  1636. // contain duplicate non-NULL values for the indexed columns.
  1637. func (m *TableManager) ValidateUniqueIndex(index *Index) error {
  1638. seen := make(map[string]bool)
  1639. return m.scanRows(index.Table, func(row Row) (bool, error) {
  1640. encoded, isNull, err := m.encodeUniqueValue(row, index.Columns)
  1641. if err != nil {
  1642. return true, err
  1643. }
  1644. if isNull {
  1645. return false, nil
  1646. }
  1647. if seen[encoded] {
  1648. return true, &UniqueViolationError{Constraint: index.Name}
  1649. }
  1650. seen[encoded] = true
  1651. return false, nil
  1652. })
  1653. }
  1654. // CreateUniqueIndex validates existing rows and registers the index while
  1655. // holding the table's exclusive gate, so a concurrent writer cannot insert a
  1656. // conflicting value between validation and registration.
  1657. func (m *TableManager) CreateUniqueIndex(index *Index) error {
  1658. tl := m.tableLock(index.Table)
  1659. tl.Lock()
  1660. defer tl.Unlock()
  1661. if err := m.ValidateUniqueIndex(index); err != nil {
  1662. return err
  1663. }
  1664. return m.schema.CreateIndex(index)
  1665. }
  1666. type indexedRowVersion struct {
  1667. row Row
  1668. key string
  1669. lsn uint64
  1670. }
  1671. type indexPredicateSnapshot struct {
  1672. valueKey string
  1673. valueGen uint64
  1674. wildcardKey string
  1675. wildcardGen uint64
  1676. }
  1677. // selectByIndexWithLSN retrieves indexed rows and their durable versions. The
  1678. // transaction layer uses the versions for optimistic commit validation.
  1679. func (m *TableManager) selectByIndexWithLSN(table, indexName string, colValue interface{}) ([]indexedRowVersion, indexPredicateSnapshot, error) {
  1680. return m.selectByIndexKeyWithLSN(table, indexName, formatIndexValue(colValue))
  1681. }
  1682. // IndexRowKey computes the formatted in-memory index key a row maps to for an
  1683. // index. Expression columns are evaluated through the same registered evaluator
  1684. // used by uniqueness enforcement, so the key matches both durable index entries
  1685. // and staged overlay rows.
  1686. func (m *TableManager) IndexRowKey(idx *Index, row Row) (string, error) {
  1687. value, err := m.buildIndexValue(row, idx.Columns)
  1688. if err != nil {
  1689. return "", err
  1690. }
  1691. return formatIndexValue(value), nil
  1692. }
  1693. // IndexValueContainsNull reports whether any column contributing to an index
  1694. // key evaluates to NULL. UNIQUE indexes exempt such rows from conflicts under
  1695. // SQLite semantics.
  1696. func (m *TableManager) IndexValueContainsNull(idx *Index, row Row) (bool, error) {
  1697. _, isNull, err := m.encodeUniqueValue(row, idx.Columns)
  1698. return isNull, err
  1699. }
  1700. // selectByIndexKeyWithLSN is selectByIndexWithLSN with an already-computed
  1701. // formatted index key, so callers can look up composite and expression indexes
  1702. // without re-deriving the key from a single column value.
  1703. func (m *TableManager) selectByIndexKeyWithLSN(table, indexName, valueKey string) ([]indexedRowVersion, indexPredicateSnapshot, error) {
  1704. index, err := m.schema.GetIndex(indexName)
  1705. if err != nil {
  1706. return nil, indexPredicateSnapshot{}, err
  1707. }
  1708. tableKey := strings.ToLower(table)
  1709. tl := m.tableLock(tableKey)
  1710. indexKey := strings.ToLower(indexName)
  1711. for {
  1712. if err := m.ensureIndex(index); err != nil {
  1713. return nil, indexPredicateSnapshot{}, err
  1714. }
  1715. tl.RLock()
  1716. if !m.schema.TableExists(table) {
  1717. tl.RUnlock()
  1718. return nil, indexPredicateSnapshot{}, fmt.Errorf("table not found: %s", table)
  1719. }
  1720. m.cacheMu.RLock()
  1721. if m.disabledIndexes[indexKey] {
  1722. m.cacheMu.RUnlock()
  1723. tl.RUnlock()
  1724. return nil, indexPredicateSnapshot{}, fmt.Errorf("%w: %s is disabled", ErrIndexNotFound, indexName)
  1725. }
  1726. if _, initialized := m.indexCache[indexKey]; initialized {
  1727. break // Keep cacheMu through the complete candidate/key snapshot.
  1728. }
  1729. m.cacheMu.RUnlock()
  1730. tl.RUnlock()
  1731. // Commits can invalidate under a shared table gate. Retry the build,
  1732. // never interpret a missing cache as a legitimately empty index.
  1733. }
  1734. defer tl.RUnlock()
  1735. predicateKey, predicateGen, wildcardKey, wildcardGen := m.predicateSnapshot(table, indexName, valueKey)
  1736. snapshot := indexPredicateSnapshot{
  1737. valueKey: predicateKey, valueGen: predicateGen,
  1738. wildcardKey: wildcardKey, wildcardGen: wildcardGen,
  1739. }
  1740. rowids := append([]int64(nil), m.indexCache[indexKey][valueKey]...)
  1741. primaryKeys := make([]string, 0, len(rowids))
  1742. missingRowID := int64(0)
  1743. missingRowKey := false
  1744. for _, rowid := range rowids {
  1745. if primaryKey, ok := m.rowKeyCache[tableKey][rowid]; ok {
  1746. primaryKeys = append(primaryKeys, primaryKey)
  1747. } else {
  1748. missingRowID = rowid
  1749. missingRowKey = true
  1750. break
  1751. }
  1752. }
  1753. m.cacheMu.RUnlock()
  1754. if missingRowKey {
  1755. return nil, indexPredicateSnapshot{}, fmt.Errorf("index %s is missing rowid %d", indexName, missingRowID)
  1756. }
  1757. // If no rowids found, return empty result
  1758. if len(rowids) == 0 {
  1759. return []indexedRowVersion{}, snapshot, nil
  1760. }
  1761. rows := make([]indexedRowVersion, 0, len(primaryKeys))
  1762. err = m.pool.WithClient(func(client *KVClient) error {
  1763. keys := make([][]byte, len(primaryKeys))
  1764. for i, primaryKey := range primaryKeys {
  1765. keys[i] = []byte(m.dataKey(table, primaryKey))
  1766. }
  1767. results, err := client.MultiGet(keys)
  1768. if err != nil {
  1769. return err
  1770. }
  1771. for i, result := range results {
  1772. if !result.Found {
  1773. primaryKey := primaryKeys[i]
  1774. return fmt.Errorf("index %s references missing primary key %s", indexName, primaryKey)
  1775. }
  1776. row, err := decodeRow(result.Value)
  1777. if err != nil {
  1778. return err
  1779. }
  1780. rows = append(rows, indexedRowVersion{
  1781. row: row,
  1782. key: m.dataKey(table, primaryKeys[i]),
  1783. lsn: result.LSN,
  1784. })
  1785. }
  1786. return nil
  1787. })
  1788. if err != nil {
  1789. return nil, indexPredicateSnapshot{}, err
  1790. }
  1791. return rows, snapshot, nil
  1792. }
  1793. // SelectByIndex retrieves rows using an in-memory equality index followed by a
  1794. // single MultiGet for the matching primary keys.
  1795. func (m *TableManager) SelectByIndex(table, indexName string, colValue interface{}) ([]Row, error) {
  1796. versions, _, err := m.selectByIndexWithLSN(table, indexName, colValue)
  1797. if err != nil {
  1798. return nil, err
  1799. }
  1800. rows := make([]Row, len(versions))
  1801. for i := range versions {
  1802. rows[i] = versions[i].row
  1803. }
  1804. return rows, nil
  1805. }