table.go 57 KB

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