table.go 56 KB

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