table.go 56 KB

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