table.go 56 KB

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