table.go 55 KB

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