table.go 55 KB

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