table.go 56 KB

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