table.go 58 KB

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