2
0

table.go 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297
  1. package storage
  2. import (
  3. "fmt"
  4. "math"
  5. "strings"
  6. "sync"
  7. "time"
  8. )
  9. // Row represents a database row.
  10. type Row map[string]interface{}
  11. // TableManager manages table data operations.
  12. type TableManager struct {
  13. pool *KVPool
  14. schema *SchemaManager
  15. database string
  16. cacheMu sync.RWMutex
  17. indexCache map[string]map[string][]int64 // index name → indexed value → rowids
  18. indexTable map[string]string // index name → table name
  19. rowKeyCache map[string]map[int64]string // table name → rowid → primary key
  20. // disabledIndexes prevents a concurrent lookup from rebuilding an index
  21. // after DROP has cleared it but before the schema entry is removed.
  22. disabledIndexes map[string]bool
  23. // counts holds exact per-table row counts for the COUNT(*) fast path.
  24. // It is derived lazily from durable rows on first use and maintained
  25. // incrementally by Insert/InsertBulk/Delete thereafter.
  26. counts map[string]int
  27. countsInit map[string]bool
  28. countGeneration map[string]time.Time
  29. }
  30. // NewTableManager creates a new table manager.
  31. func NewTableManager(pool *KVPool, schema *SchemaManager, database string) *TableManager {
  32. return &TableManager{
  33. pool: pool,
  34. schema: schema,
  35. database: database,
  36. indexCache: make(map[string]map[string][]int64),
  37. indexTable: make(map[string]string),
  38. rowKeyCache: make(map[string]map[int64]string),
  39. disabledIndexes: make(map[string]bool),
  40. counts: make(map[string]int),
  41. countsInit: make(map[string]bool),
  42. countGeneration: make(map[string]time.Time),
  43. }
  44. }
  45. func (m *TableManager) tableLock(key string) *sync.RWMutex {
  46. return m.schema.tableLock(key)
  47. }
  48. // invalidateCache removes a table's derived in-memory indexes.
  49. func (m *TableManager) invalidateCache(table string) {
  50. m.cacheMu.Lock()
  51. key := strings.ToLower(table)
  52. delete(m.rowKeyCache, key)
  53. delete(m.counts, key)
  54. delete(m.countsInit, key)
  55. delete(m.countGeneration, key)
  56. for indexName, tableName := range m.indexTable {
  57. if tableName == key {
  58. delete(m.indexCache, indexName)
  59. delete(m.indexTable, indexName)
  60. }
  61. }
  62. m.cacheMu.Unlock()
  63. }
  64. // InvalidateCache is the exported version for use by the executor.
  65. func (m *TableManager) InvalidateCache(table string) {
  66. m.invalidateCache(table)
  67. }
  68. // rowVisitFunc is invoked for each decoded row in a streaming scan. Return
  69. // stop=true to end the scan early; a non-nil error aborts the scan.
  70. type rowVisitFunc func(Row) (stop bool, err error)
  71. // scanRows streams the rows of table by scanning durable KV rows one page at a
  72. // time under a single pooled client. Each page is decoded as it arrives and
  73. // passed to fn, which may stop the scan early. The cursor is always closed and
  74. // the client always returned to the pool, even on error.
  75. func (m *TableManager) scanRows(table string, fn rowVisitFunc) error {
  76. return m.scanRowsWithPageSize(table, scanPageSize, fn)
  77. }
  78. func (m *TableManager) scanRowsWithPageSize(table string, pageSize uint32, fn rowVisitFunc) error {
  79. return m.pool.WithClient(func(client *KVClient) (retErr error) {
  80. cursor, err := client.ScanWithLimit([]byte(m.dataPrefix(table)), pageSize)
  81. if err != nil {
  82. return err
  83. }
  84. defer func() {
  85. if err := cursor.Close(); retErr == nil {
  86. retErr = err
  87. }
  88. }()
  89. for {
  90. entries, done, err := cursor.Next()
  91. if err != nil {
  92. return err
  93. }
  94. for _, e := range entries {
  95. row, err := decodeRow(e.Value)
  96. if err != nil {
  97. return err
  98. }
  99. stop, err := fn(row)
  100. if err != nil {
  101. return err
  102. }
  103. if stop {
  104. return nil
  105. }
  106. }
  107. if done {
  108. return nil
  109. }
  110. }
  111. })
  112. }
  113. // scanCountKeys counts the durable rows of table using a key-only scan so row
  114. // values are never pulled across the wire. It is used for first-time COUNT(*)
  115. // derivation.
  116. func (m *TableManager) scanCountKeys(table string) (int, error) {
  117. count := 0
  118. err := m.pool.WithClient(func(client *KVClient) (retErr error) {
  119. cursor, err := client.ScanKeys([]byte(m.dataPrefix(table)))
  120. if err != nil {
  121. return err
  122. }
  123. defer func() {
  124. if err := cursor.Close(); retErr == nil {
  125. retErr = err
  126. }
  127. }()
  128. for {
  129. entries, done, err := cursor.Next()
  130. if err != nil {
  131. return err
  132. }
  133. count += len(entries)
  134. if done {
  135. return nil
  136. }
  137. }
  138. })
  139. return count, err
  140. }
  141. // CountFast returns the exact number of rows in a table. The count is derived
  142. // from durable rows on first use (recovering across restarts) and then
  143. // maintained incrementally by the write paths, so repeated COUNT(*) queries
  144. // avoid a full table scan. It intentionally does not persist a counter to KV:
  145. // the KV layer has no atomic increment primitive, and a durable counter that
  146. // could diverge from the rows on crash would be worse than a lazily-derived,
  147. // always-exact value. The cost is one key-only scan the first time COUNT(*) is
  148. // issued after startup.
  149. func (m *TableManager) CountFast(table string) (int, error) {
  150. key := strings.ToLower(table)
  151. tl := m.tableLock(key)
  152. tl.Lock()
  153. defer tl.Unlock()
  154. tableSchema, err := m.schema.GetSchema(table)
  155. if err != nil {
  156. return 0, err
  157. }
  158. m.cacheMu.Lock()
  159. if !m.countGeneration[key].Equal(tableSchema.CreatedAt) {
  160. delete(m.counts, key)
  161. delete(m.countsInit, key)
  162. m.countGeneration[key] = tableSchema.CreatedAt
  163. }
  164. init := m.countsInit[key]
  165. n := m.counts[key]
  166. m.cacheMu.Unlock()
  167. if init {
  168. return n, nil
  169. }
  170. count, err := m.scanCountKeys(table)
  171. if err != nil {
  172. return 0, err
  173. }
  174. m.cacheMu.Lock()
  175. m.counts[key] = count
  176. m.countsInit[key] = true
  177. m.cacheMu.Unlock()
  178. return count, nil
  179. }
  180. // incrCount adjusts the derived per-table row count. It is a no-op until the
  181. // count has been initialized, since an uninitialized count is re-derived from
  182. // durable rows (which already reflect the write) on next use.
  183. func (m *TableManager) incrCount(table string, generation time.Time, delta int) {
  184. key := strings.ToLower(table)
  185. m.cacheMu.Lock()
  186. if !m.countGeneration[key].Equal(generation) {
  187. delete(m.counts, key)
  188. delete(m.countsInit, key)
  189. m.countGeneration[key] = generation
  190. }
  191. if m.countsInit[key] {
  192. m.counts[key] += delta
  193. }
  194. m.cacheMu.Unlock()
  195. }
  196. // dataKey returns the key for a row.
  197. func (m *TableManager) dataKey(table, pk string) string {
  198. return fmt.Sprintf("%s:_data:%s:%s", m.database, strings.ToLower(table), pk)
  199. }
  200. // dataPrefix returns the prefix for all rows in a table.
  201. func (m *TableManager) dataPrefix(table string) string {
  202. return fmt.Sprintf("%s:_data:%s:", m.database, strings.ToLower(table))
  203. }
  204. // Insert inserts a new row.
  205. func (m *TableManager) Insert(table string, row Row) error {
  206. tl := m.tableLock(table)
  207. tl.Lock()
  208. defer tl.Unlock()
  209. schema, err := m.schema.GetSchema(table)
  210. if err != nil {
  211. return err
  212. }
  213. // Get primary key value
  214. pkValue, ok := row[schema.PrimaryKey]
  215. if !ok {
  216. // Try case-insensitive lookup
  217. for k, v := range row {
  218. if strings.EqualFold(k, schema.PrimaryKey) {
  219. pkValue = v
  220. ok = true
  221. break
  222. }
  223. }
  224. }
  225. // Check if PK is INTEGER PRIMARY KEY (implicit ROWID alias)
  226. pkCol, _ := schema.GetColumn(schema.PrimaryKey)
  227. isIntegerPK := pkCol != nil && isIntegerType(pkCol.Type)
  228. // Auto-generate ROWID if no primary key provided or if it's INTEGER PRIMARY KEY
  229. var rowid int64
  230. if !ok || pkValue == nil {
  231. if isIntegerPK || !ok {
  232. // Generate ROWID
  233. rowid, err = m.schema.GetNextRowID(table)
  234. if err != nil {
  235. return err
  236. }
  237. pkValue = rowid
  238. row[schema.PrimaryKey] = rowid
  239. ok = true
  240. } else {
  241. return fmt.Errorf("missing primary key: %s", schema.PrimaryKey)
  242. }
  243. } else if isIntegerPK {
  244. // User provided INTEGER PRIMARY KEY value - track it
  245. switch v := pkValue.(type) {
  246. case int64:
  247. rowid = v
  248. case float64:
  249. if math.Trunc(v) != v {
  250. return fmt.Errorf("invalid integer primary key: %v", v)
  251. }
  252. rowid = int64(v)
  253. case int:
  254. rowid = int64(v)
  255. default:
  256. rowid = 0
  257. }
  258. if rowid > 0 {
  259. m.schema.UpdateMaxRowID(table, rowid)
  260. }
  261. }
  262. pk := fmt.Sprintf("%v", pkValue)
  263. // Keep the duplicate check and write in one per-table critical section so
  264. // concurrent inserts of the same primary key cannot both persist a single
  265. // durable row and double-count it.
  266. key := m.dataKey(table, pk)
  267. var exists bool
  268. err = m.pool.WithClient(func(c *KVClient) error {
  269. var e error
  270. exists, e = c.Exists([]byte(key))
  271. return e
  272. })
  273. if err != nil {
  274. return err
  275. }
  276. if exists {
  277. return fmt.Errorf("duplicate primary key: %s", pk)
  278. }
  279. // Validate required columns
  280. for _, col := range schema.Columns {
  281. if !col.Nullable && col.Default == nil {
  282. val, hasVal := row[col.Name]
  283. if !hasVal {
  284. // Try case-insensitive lookup
  285. for k, v := range row {
  286. if strings.EqualFold(k, col.Name) {
  287. val = v
  288. hasVal = true
  289. break
  290. }
  291. }
  292. }
  293. if !hasVal || val == nil {
  294. return fmt.Errorf("missing required column: %s", col.Name)
  295. }
  296. }
  297. }
  298. // Normalize column names to match schema
  299. normalizedRow := make(Row)
  300. for _, col := range schema.Columns {
  301. for k, v := range row {
  302. if strings.EqualFold(k, col.Name) {
  303. normalizedRow[col.Name] = v
  304. break
  305. }
  306. }
  307. }
  308. // Apply defaults
  309. for _, col := range schema.Columns {
  310. if _, ok := normalizedRow[col.Name]; !ok && col.Default != nil {
  311. normalizedRow[col.Name] = col.Default
  312. }
  313. }
  314. // Store ROWID (use PK value for INTEGER PRIMARY KEY, otherwise generate)
  315. if rowid > 0 {
  316. normalizedRow["_rowid_"] = rowid
  317. } else {
  318. // Generate ROWID for non-integer primary keys
  319. newRowID, _ := m.schema.GetNextRowID(table)
  320. normalizedRow["_rowid_"] = newRowID
  321. }
  322. // Serialize row
  323. data, err := encodeRow(normalizedRow)
  324. if err != nil {
  325. return fmt.Errorf("failed to serialize row: %w", err)
  326. }
  327. err = m.pool.WithClient(func(c *KVClient) error {
  328. _, err := c.Put([]byte(key), data)
  329. return err
  330. })
  331. if err != nil {
  332. return err
  333. }
  334. // Update in-memory indexes only. Durable index entries are derived from rows.
  335. m.updateIndexesForRow(table, normalizedRow, true)
  336. m.incrCount(table, schema.CreatedAt, 1)
  337. return nil
  338. }
  339. // bulkBatchByteBudget bounds a single atomic BATCH_WRITE payload below the
  340. // PKBFI frame limit so a bulk insert never emits a frame the server rejects.
  341. // Each op contributes 12 header bytes plus its key and value.
  342. const bulkBatchByteBudget = 60 * 1024 * 1024
  343. // chunkBatchOps splits ops into atomic BATCH_WRITE chunks bounded by both the
  344. // PKBFI operation-count limit and the frame-size limit. Each chunk is a slice
  345. // of the backing array, valid until the next append to ops.
  346. func chunkBatchOps(ops []BatchOp) [][]BatchOp {
  347. var chunks [][]BatchOp
  348. for i := 0; i < len(ops); {
  349. end := i + maxOperations
  350. if end > len(ops) {
  351. end = len(ops)
  352. }
  353. bytes := 0
  354. j := i
  355. for j < end {
  356. sz := 12 + len(ops[j].Key) + len(ops[j].Value)
  357. if j > i && bytes+sz > bulkBatchByteBudget {
  358. break
  359. }
  360. bytes += sz
  361. j++
  362. }
  363. if j == i {
  364. j = i + 1
  365. }
  366. chunks = append(chunks, ops[i:j])
  367. i = j
  368. }
  369. return chunks
  370. }
  371. // InsertBulk inserts multiple rows efficiently using atomic BATCH_WRITE chunks
  372. // bounded by the PKBFI operation-count and frame-size limits. Skips per-row
  373. // duplicate checks (caller must ensure uniqueness). Used by INSERT ... SELECT.
  374. func (m *TableManager) InsertBulk(table string, rows []Row) (int, error) {
  375. if len(rows) == 0 {
  376. return 0, nil
  377. }
  378. tl := m.tableLock(table)
  379. tl.Lock()
  380. defer tl.Unlock()
  381. schema, err := m.schema.GetSchema(table)
  382. if err != nil {
  383. return 0, err
  384. }
  385. pkCol, _ := schema.GetColumn(schema.PrimaryKey)
  386. isIntegerPK := pkCol != nil && isIntegerType(pkCol.Type)
  387. // Normalize rows and assign _rowid_.
  388. normalized := make([]Row, 0, len(rows))
  389. var maxRowID int64
  390. for _, row := range rows {
  391. nr := make(Row)
  392. for _, col := range schema.Columns {
  393. for k, v := range row {
  394. if strings.EqualFold(k, col.Name) {
  395. nr[col.Name] = v
  396. break
  397. }
  398. }
  399. }
  400. for _, col := range schema.Columns {
  401. if _, ok := nr[col.Name]; !ok && col.Default != nil {
  402. nr[col.Name] = col.Default
  403. }
  404. }
  405. var rowid int64
  406. var hasRowid bool
  407. if isIntegerPK {
  408. switch v := nr[schema.PrimaryKey].(type) {
  409. case float64:
  410. if math.Trunc(v) != v {
  411. return 0, fmt.Errorf("invalid integer primary key: %v", v)
  412. }
  413. rowid = int64(v)
  414. hasRowid = true
  415. case int64:
  416. rowid = v
  417. hasRowid = true
  418. case int:
  419. rowid = int64(v)
  420. hasRowid = true
  421. }
  422. }
  423. if !hasRowid {
  424. if schema.PrimaryKey != "_rowid_" {
  425. pk, ok := nr[schema.PrimaryKey]
  426. if !ok || pk == nil {
  427. return 0, fmt.Errorf("missing primary key: %s", schema.PrimaryKey)
  428. }
  429. }
  430. rowid, err = m.schema.GetNextRowID(table)
  431. if err != nil {
  432. return 0, err
  433. }
  434. if schema.PrimaryKey == "_rowid_" {
  435. nr[schema.PrimaryKey] = rowid
  436. }
  437. }
  438. nr["_rowid_"] = rowid
  439. if rowid > maxRowID {
  440. maxRowID = rowid
  441. }
  442. normalized = append(normalized, nr)
  443. }
  444. if maxRowID > 0 {
  445. m.schema.UpdateMaxRowID(table, maxRowID)
  446. }
  447. // Serialize all rows into batch operations. A parallel slice keeps the
  448. // normalized Row for each op for index maintenance after the write.
  449. ops := make([]BatchOp, 0, len(normalized))
  450. encoded := make([]Row, 0, len(normalized))
  451. for _, nr := range normalized {
  452. pk := fmt.Sprintf("%v", nr[schema.PrimaryKey])
  453. data, err := encodeRow(nr)
  454. if err != nil {
  455. return 0, err
  456. }
  457. ops = append(ops, BatchOp{Op: batchPut, Key: []byte(m.dataKey(table, pk)), Value: data})
  458. encoded = append(encoded, nr)
  459. }
  460. keys := make([][]byte, len(ops))
  461. seen := make(map[string]struct{}, len(ops))
  462. for i, op := range ops {
  463. key := string(op.Key)
  464. if _, duplicate := seen[key]; duplicate {
  465. return 0, fmt.Errorf("duplicate primary key: %s", key)
  466. }
  467. seen[key] = struct{}{}
  468. keys[i] = op.Key
  469. }
  470. existing := make([]bool, len(keys))
  471. if err := m.pool.WithClient(func(client *KVClient) error {
  472. for start := 0; start < len(keys); start += maxOperations {
  473. end := start + maxOperations
  474. if end > len(keys) {
  475. end = len(keys)
  476. }
  477. found, err := client.ExistsMany(keys[start:end])
  478. if err != nil {
  479. return err
  480. }
  481. copy(existing[start:end], found)
  482. }
  483. return nil
  484. }); err != nil {
  485. return 0, err
  486. }
  487. for i, found := range existing {
  488. if found {
  489. return 0, fmt.Errorf("duplicate primary key: %s", ops[i].Key)
  490. }
  491. }
  492. // Write rows in atomic BATCH_WRITE chunks. Maintain in-memory indexes only
  493. // for rows that actually persisted, so a partial failure cannot leave an
  494. // already-built index stale.
  495. var firstErr error
  496. numOK := 0
  497. for _, chunk := range chunkBatchOps(ops) {
  498. err := m.pool.WithClient(func(c *KVClient) error {
  499. _, err := c.BatchWrite(chunk, nil)
  500. return err
  501. })
  502. if err != nil {
  503. if firstErr == nil {
  504. firstErr = err
  505. }
  506. break
  507. }
  508. numOK += len(chunk)
  509. }
  510. // Maintain indexes for the rows that persisted (the first numOK ops).
  511. for i := 0; i < numOK; i++ {
  512. m.updateIndexesForRow(table, encoded[i], true)
  513. }
  514. m.incrCount(table, schema.CreatedAt, numOK)
  515. return numOK, firstErr
  516. }
  517. // updateIndexesForRow adds or removes entries from already-built in-memory
  518. // indexes. Index entries are rebuildable from durable row data, so this method
  519. // intentionally does not write idx:* keys to KV.
  520. func (m *TableManager) updateIndexesForRow(table string, row Row, add bool) {
  521. indexes, err := m.schema.ListTableIndexes(table)
  522. if err != nil || len(indexes) == 0 {
  523. return
  524. }
  525. rowid, ok := rowIDFromRow(row)
  526. if !ok {
  527. return
  528. }
  529. tableKey := strings.ToLower(table)
  530. tableSchema, schemaErr := m.schema.GetSchema(table)
  531. if schemaErr == nil {
  532. m.cacheMu.Lock()
  533. if keys, initialized := m.rowKeyCache[tableKey]; initialized {
  534. if add {
  535. keys[rowid] = fmt.Sprintf("%v", row[tableSchema.PrimaryKey])
  536. } else {
  537. delete(keys, rowid)
  538. }
  539. }
  540. m.cacheMu.Unlock()
  541. }
  542. for _, idx := range indexes {
  543. indexName := strings.ToLower(idx.Name)
  544. m.cacheMu.RLock()
  545. _, initialized := m.indexCache[indexName]
  546. m.cacheMu.RUnlock()
  547. if !initialized {
  548. continue
  549. }
  550. columns := make([]string, len(idx.Columns))
  551. for i, col := range idx.Columns {
  552. columns[i] = col.Name
  553. }
  554. colValue := m.buildIndexValue(row, columns)
  555. if add {
  556. m.AddIndexEntry(idx.Name, colValue, rowid)
  557. } else {
  558. m.RemoveIndexEntry(idx.Name, colValue, rowid)
  559. }
  560. }
  561. }
  562. // Select retrieves rows from a table by scanning durable rows and collecting
  563. // only matching rows.
  564. func (m *TableManager) Select(table string, filter func(Row) bool) ([]Row, error) {
  565. tl := m.tableLock(table)
  566. tl.RLock()
  567. defer tl.RUnlock()
  568. if !m.schema.TableExists(table) {
  569. return nil, fmt.Errorf("table not found: %s", table)
  570. }
  571. rows := make([]Row, 0)
  572. err := m.scanRows(table, func(row Row) (bool, error) {
  573. if filter == nil || filter(row) {
  574. rows = append(rows, row)
  575. }
  576. return false, nil
  577. })
  578. if err != nil {
  579. return nil, err
  580. }
  581. return rows, nil
  582. }
  583. func cloneRow(row Row) Row {
  584. if row == nil {
  585. return nil
  586. }
  587. cloned := make(Row, len(row))
  588. for k, v := range row {
  589. cloned[k] = v
  590. }
  591. return cloned
  592. }
  593. // SelectWithLimit retrieves rows with limit and offset, applying filter/offset
  594. // while scanning and closing the scan early once the limit is reached.
  595. func (m *TableManager) SelectWithLimit(table string, filter func(Row) bool, limit, offset int) ([]Row, error) {
  596. tl := m.tableLock(table)
  597. tl.RLock()
  598. defer tl.RUnlock()
  599. if !m.schema.TableExists(table) {
  600. return nil, fmt.Errorf("table not found: %s", table)
  601. }
  602. rows := make([]Row, 0)
  603. skipped := 0
  604. pageSize := scanPageSize
  605. if limit > 0 {
  606. desired := limit
  607. if offset > 0 {
  608. if offset >= scanPageSize-desired {
  609. desired = scanPageSize
  610. } else {
  611. desired += offset
  612. }
  613. }
  614. if desired < 1 {
  615. desired = 1
  616. }
  617. if desired < pageSize {
  618. pageSize = desired
  619. }
  620. }
  621. err := m.scanRowsWithPageSize(table, uint32(pageSize), func(row Row) (bool, error) {
  622. if filter != nil && !filter(row) {
  623. return false, nil
  624. }
  625. if skipped < offset {
  626. skipped++
  627. return false, nil
  628. }
  629. rows = append(rows, row)
  630. return limit > 0 && len(rows) >= limit, nil
  631. })
  632. if err != nil {
  633. return nil, err
  634. }
  635. return rows, nil
  636. }
  637. // Update updates rows matching the filter.
  638. func (m *TableManager) Update(table string, updates Row, filter func(Row) bool) (int, error) {
  639. // Get all rows
  640. rows, err := m.Select(table, filter)
  641. if err != nil {
  642. return 0, err
  643. }
  644. tl := m.tableLock(strings.ToLower(table))
  645. tl.Lock()
  646. defer tl.Unlock()
  647. schema, err := m.schema.GetSchema(table)
  648. if err != nil {
  649. return 0, err
  650. }
  651. count := 0
  652. for _, row := range rows {
  653. // Snapshot the pre-update row so removed index entries can be restored
  654. // if persistence fails.
  655. oldRow := cloneRow(row)
  656. m.updateIndexesForRow(table, row, false)
  657. // Apply updates
  658. for k, v := range updates {
  659. // Normalize column name
  660. for _, col := range schema.Columns {
  661. if strings.EqualFold(k, col.Name) {
  662. row[col.Name] = v
  663. break
  664. }
  665. }
  666. }
  667. // Get primary key
  668. pkValue := row[schema.PrimaryKey]
  669. pk := fmt.Sprintf("%v", pkValue)
  670. // Serialize row
  671. data, err := encodeRow(row)
  672. if err != nil {
  673. m.updateIndexesForRow(table, oldRow, true)
  674. continue
  675. }
  676. // Write back
  677. key := m.dataKey(table, pk)
  678. err = m.pool.WithClient(func(c *KVClient) error {
  679. _, err := c.Put([]byte(key), data)
  680. return err
  681. })
  682. if err == nil {
  683. // Add new index entries after update
  684. m.updateIndexesForRow(table, row, true)
  685. count++
  686. } else {
  687. m.updateIndexesForRow(table, oldRow, true)
  688. }
  689. }
  690. return count, nil
  691. }
  692. // UpdateFunc updates rows matching the filter using a function to compute new values.
  693. // The updateFn receives the current row and returns the updates to apply.
  694. func (m *TableManager) UpdateFunc(table string, updateFn func(Row) (Row, error), filter func(Row) bool) (int, error) {
  695. // Get all rows
  696. rows, err := m.Select(table, filter)
  697. if err != nil {
  698. return 0, err
  699. }
  700. tl := m.tableLock(strings.ToLower(table))
  701. tl.Lock()
  702. defer tl.Unlock()
  703. schema, err := m.schema.GetSchema(table)
  704. if err != nil {
  705. return 0, err
  706. }
  707. count := 0
  708. for _, row := range rows {
  709. oldRow := cloneRow(row)
  710. m.updateIndexesForRow(table, row, false)
  711. // Compute updates using the provided function
  712. updates, err := updateFn(row)
  713. if err != nil {
  714. m.updateIndexesForRow(table, oldRow, true)
  715. return count, err
  716. }
  717. // Apply updates
  718. for k, v := range updates {
  719. // Normalize column name
  720. for _, col := range schema.Columns {
  721. if strings.EqualFold(k, col.Name) {
  722. row[col.Name] = v
  723. break
  724. }
  725. }
  726. }
  727. // Get primary key
  728. pkValue := row[schema.PrimaryKey]
  729. pk := fmt.Sprintf("%v", pkValue)
  730. // Serialize row
  731. data, err := encodeRow(row)
  732. if err != nil {
  733. m.updateIndexesForRow(table, oldRow, true)
  734. continue
  735. }
  736. // Write back
  737. key := m.dataKey(table, pk)
  738. err = m.pool.WithClient(func(c *KVClient) error {
  739. _, err := c.Put([]byte(key), data)
  740. return err
  741. })
  742. if err == nil {
  743. // Add new index entries after update
  744. m.updateIndexesForRow(table, row, true)
  745. count++
  746. } else {
  747. m.updateIndexesForRow(table, oldRow, true)
  748. }
  749. }
  750. return count, nil
  751. }
  752. // Delete deletes rows matching the filter.
  753. func (m *TableManager) Delete(table string, filter func(Row) bool) (int, error) {
  754. // Get all rows
  755. rows, err := m.Select(table, filter)
  756. if err != nil {
  757. return 0, err
  758. }
  759. tl := m.tableLock(strings.ToLower(table))
  760. tl.Lock()
  761. defer tl.Unlock()
  762. schema, err := m.schema.GetSchema(table)
  763. if err != nil {
  764. return 0, err
  765. }
  766. count := 0
  767. for _, row := range rows {
  768. // Remove index entries before deleting row
  769. m.updateIndexesForRow(table, row, false)
  770. pkValue := row[schema.PrimaryKey]
  771. pk := fmt.Sprintf("%v", pkValue)
  772. key := m.dataKey(table, pk)
  773. err = m.pool.WithClient(func(c *KVClient) error {
  774. _, err := c.Del([]byte(key))
  775. return err
  776. })
  777. if err == nil {
  778. count++
  779. } else {
  780. // Restore the index entries removed above.
  781. m.updateIndexesForRow(table, row, true)
  782. }
  783. }
  784. m.incrCount(table, schema.CreatedAt, -count)
  785. return count, nil
  786. }
  787. // GetByPK retrieves a row by primary key.
  788. func (m *TableManager) GetByPK(table string, pk string) (Row, error) {
  789. tl := m.tableLock(table)
  790. tl.RLock()
  791. defer tl.RUnlock()
  792. if !m.schema.TableExists(table) {
  793. return nil, fmt.Errorf("table not found: %s", table)
  794. }
  795. key := m.dataKey(table, pk)
  796. var value []byte
  797. err := m.pool.WithClient(func(c *KVClient) error {
  798. res, err := c.Get([]byte(key))
  799. if err != nil {
  800. return err
  801. }
  802. value = res.Value
  803. return nil
  804. })
  805. if err != nil {
  806. if err == ErrKeyNotFound {
  807. return nil, fmt.Errorf("row not found: %s", pk)
  808. }
  809. return nil, err
  810. }
  811. row, err := decodeRow(value)
  812. if err != nil {
  813. return nil, fmt.Errorf("failed to parse row: %w", err)
  814. }
  815. return row, nil
  816. }
  817. // Count returns the number of rows in a table matching the filter.
  818. func (m *TableManager) Count(table string, filter func(Row) bool) (int, error) {
  819. tl := m.tableLock(table)
  820. tl.RLock()
  821. defer tl.RUnlock()
  822. if !m.schema.TableExists(table) {
  823. return 0, fmt.Errorf("table not found: %s", table)
  824. }
  825. count := 0
  826. err := m.scanRows(table, func(row Row) (bool, error) {
  827. if filter == nil || filter(row) {
  828. count++
  829. }
  830. return false, nil
  831. })
  832. if err != nil {
  833. return 0, err
  834. }
  835. return count, nil
  836. }
  837. // Truncate removes all rows from a table.
  838. func (m *TableManager) Truncate(table string) (int, error) {
  839. return m.Delete(table, nil)
  840. }
  841. // isIntegerType checks if a type name is an integer type.
  842. func isIntegerType(typeName string) bool {
  843. t := strings.ToUpper(typeName)
  844. switch t {
  845. case "INTEGER", "INT", "SMALLINT", "BIGINT", "TINYINT", "MEDIUMINT":
  846. return true
  847. }
  848. return false
  849. }
  850. // IsRowIDColumn checks if a column name is a ROWID alias.
  851. func IsRowIDColumn(name string) bool {
  852. n := strings.ToLower(name)
  853. return n == "rowid" || n == "oid" || n == "_rowid_"
  854. }
  855. // Index entry methods - leveraging radix trie for prefix-based lookups
  856. // Format: {database}:idx:{index_name}:{column_value} → JSON array of rowids
  857. // indexEntryKey returns the key for an index entry.
  858. func (m *TableManager) indexEntryKey(indexName string, colValue interface{}) string {
  859. return fmt.Sprintf("%s:idx:%s:%s", m.database, strings.ToLower(indexName), formatIndexValue(colValue))
  860. }
  861. // indexPrefix returns the prefix for all entries of an index.
  862. func (m *TableManager) indexPrefix(indexName string) string {
  863. return fmt.Sprintf("%s:idx:%s:", m.database, strings.ToLower(indexName))
  864. }
  865. func formatIndexValue(value interface{}) string {
  866. switch v := value.(type) {
  867. case float64:
  868. if v == float64(int64(v)) {
  869. return fmt.Sprintf("%d", int64(v))
  870. }
  871. return fmt.Sprintf("%f", v)
  872. case int64:
  873. return fmt.Sprintf("%d", v)
  874. case int:
  875. return fmt.Sprintf("%d", v)
  876. default:
  877. return fmt.Sprintf("%v", v)
  878. }
  879. }
  880. func rowIDFromRow(row Row) (int64, bool) {
  881. switch v := row["_rowid_"].(type) {
  882. case int64:
  883. return v, true
  884. case int:
  885. return int64(v), true
  886. case float64:
  887. return int64(v), true
  888. default:
  889. return 0, false
  890. }
  891. }
  892. func (m *TableManager) ensureIndex(index *Index) error {
  893. indexKey := strings.ToLower(index.Name)
  894. m.cacheMu.RLock()
  895. disabled := m.disabledIndexes[indexKey]
  896. _, initialized := m.indexCache[indexKey]
  897. m.cacheMu.RUnlock()
  898. if disabled {
  899. return nil
  900. }
  901. if initialized {
  902. return nil
  903. }
  904. // Serialize index build against writes to the same table so the derived
  905. // entries cannot miss a concurrently-inserted row.
  906. table := index.Table
  907. key := strings.ToLower(table)
  908. tl := m.tableLock(key)
  909. tl.Lock()
  910. defer tl.Unlock()
  911. m.cacheMu.RLock()
  912. disabled = m.disabledIndexes[indexKey]
  913. _, initialized = m.indexCache[indexKey]
  914. m.cacheMu.RUnlock()
  915. if disabled {
  916. return nil
  917. }
  918. if initialized {
  919. return nil
  920. }
  921. columns := make([]string, len(index.Columns))
  922. for i, col := range index.Columns {
  923. columns[i] = col.Name
  924. }
  925. tableSchema, err := m.schema.GetSchema(table)
  926. if err != nil {
  927. return err
  928. }
  929. values := make(map[string][]int64)
  930. rowKeys := make(map[int64]string)
  931. if err := m.scanRows(table, func(row Row) (bool, error) {
  932. rowid, ok := rowIDFromRow(row)
  933. if !ok {
  934. return false, nil
  935. }
  936. colValue := m.buildIndexValue(row, columns)
  937. valueKey := formatIndexValue(colValue)
  938. values[valueKey] = append(values[valueKey], rowid)
  939. rowKeys[rowid] = fmt.Sprintf("%v", row[tableSchema.PrimaryKey])
  940. return false, nil
  941. }); err != nil {
  942. return err
  943. }
  944. m.cacheMu.Lock()
  945. if _, initialized := m.indexCache[indexKey]; !initialized {
  946. m.indexCache[indexKey] = values
  947. m.indexTable[indexKey] = key
  948. m.rowKeyCache[key] = rowKeys
  949. }
  950. m.cacheMu.Unlock()
  951. return nil
  952. }
  953. // AddIndexEntry adds a rowid to an in-memory index entry.
  954. func (m *TableManager) AddIndexEntry(indexName string, colValue interface{}, rowid int64) error {
  955. indexKey := strings.ToLower(indexName)
  956. valueKey := formatIndexValue(colValue)
  957. m.cacheMu.Lock()
  958. defer m.cacheMu.Unlock()
  959. values, ok := m.indexCache[indexKey]
  960. if !ok {
  961. return nil
  962. }
  963. rowids := values[valueKey]
  964. for _, r := range rowids {
  965. if r == rowid {
  966. return nil
  967. }
  968. }
  969. values[valueKey] = append(rowids, rowid)
  970. return nil
  971. }
  972. // RemoveIndexEntry removes a rowid from an in-memory index entry.
  973. func (m *TableManager) RemoveIndexEntry(indexName string, colValue interface{}, rowid int64) error {
  974. indexKey := strings.ToLower(indexName)
  975. valueKey := formatIndexValue(colValue)
  976. m.cacheMu.Lock()
  977. defer m.cacheMu.Unlock()
  978. values, ok := m.indexCache[indexKey]
  979. if !ok {
  980. return nil
  981. }
  982. rowids := values[valueKey]
  983. newRowids := make([]int64, 0, len(rowids))
  984. for _, r := range rowids {
  985. if r != rowid {
  986. newRowids = append(newRowids, r)
  987. }
  988. }
  989. if len(newRowids) == 0 {
  990. delete(values, valueKey)
  991. return nil
  992. }
  993. values[valueKey] = newRowids
  994. return nil
  995. }
  996. // LookupIndex returns rowids matching a column value using the index.
  997. func (m *TableManager) LookupIndex(indexName string, colValue interface{}) ([]int64, error) {
  998. index, err := m.schema.GetIndex(indexName)
  999. if err != nil {
  1000. return nil, err
  1001. }
  1002. if err := m.ensureIndex(index); err != nil {
  1003. return nil, err
  1004. }
  1005. indexKey := strings.ToLower(indexName)
  1006. valueKey := formatIndexValue(colValue)
  1007. m.cacheMu.RLock()
  1008. rowids := append([]int64(nil), m.indexCache[indexKey][valueKey]...)
  1009. m.cacheMu.RUnlock()
  1010. return rowids, nil
  1011. }
  1012. // ClearIndex removes an index's in-memory entries and marks it disabled so a
  1013. // concurrent lookup cannot rebuild it after DROP but before the schema entry
  1014. // is removed. Index entries are derived from durable rows, so there is nothing
  1015. // durable to delete here.
  1016. func (m *TableManager) ClearIndex(indexName, tableName string, columns []string) error {
  1017. indexKey := strings.ToLower(indexName)
  1018. tableKey := strings.ToLower(tableName)
  1019. m.cacheMu.Lock()
  1020. delete(m.indexCache, indexKey)
  1021. delete(m.indexTable, indexKey)
  1022. m.disabledIndexes[indexKey] = true
  1023. rowKeysNeeded := false
  1024. for _, indexedTable := range m.indexTable {
  1025. if indexedTable == tableKey {
  1026. rowKeysNeeded = true
  1027. break
  1028. }
  1029. }
  1030. if !rowKeysNeeded {
  1031. delete(m.rowKeyCache, tableKey)
  1032. }
  1033. m.cacheMu.Unlock()
  1034. return nil
  1035. }
  1036. // BuildIndex builds index entries for all existing rows in a table.
  1037. func (m *TableManager) BuildIndex(indexName, tableName string, columns []string) error {
  1038. indexKey := strings.ToLower(indexName)
  1039. m.cacheMu.Lock()
  1040. delete(m.disabledIndexes, indexKey)
  1041. delete(m.indexCache, indexKey)
  1042. delete(m.indexTable, indexKey)
  1043. m.cacheMu.Unlock()
  1044. index, err := m.schema.GetIndex(indexName)
  1045. if err == nil {
  1046. return m.ensureIndex(index)
  1047. }
  1048. tableSchema, schemaErr := m.schema.GetSchema(tableName)
  1049. if schemaErr != nil {
  1050. return schemaErr
  1051. }
  1052. values := make(map[string][]int64)
  1053. rowKeys := make(map[int64]string)
  1054. if err := m.scanRows(tableName, func(row Row) (bool, error) {
  1055. rowid, ok := rowIDFromRow(row)
  1056. if !ok {
  1057. return false, nil
  1058. }
  1059. colValue := m.buildIndexValue(row, columns)
  1060. values[formatIndexValue(colValue)] = append(values[formatIndexValue(colValue)], rowid)
  1061. rowKeys[rowid] = fmt.Sprintf("%v", row[tableSchema.PrimaryKey])
  1062. return false, nil
  1063. }); err != nil {
  1064. return err
  1065. }
  1066. m.cacheMu.Lock()
  1067. m.indexCache[indexKey] = values
  1068. m.indexTable[indexKey] = strings.ToLower(tableName)
  1069. m.rowKeyCache[strings.ToLower(tableName)] = rowKeys
  1070. m.cacheMu.Unlock()
  1071. return nil
  1072. }
  1073. // buildIndexValue creates the index key value from row columns.
  1074. func (m *TableManager) buildIndexValue(row Row, columns []string) string {
  1075. formatValue := func(v interface{}) string {
  1076. switch val := v.(type) {
  1077. case float64:
  1078. // Check if it's actually an integer value
  1079. if val == float64(int64(val)) {
  1080. return fmt.Sprintf("%d", int64(val))
  1081. }
  1082. return fmt.Sprintf("%f", val)
  1083. case int64:
  1084. return fmt.Sprintf("%d", val)
  1085. case int:
  1086. return fmt.Sprintf("%d", val)
  1087. default:
  1088. return fmt.Sprintf("%v", val)
  1089. }
  1090. }
  1091. if len(columns) == 1 {
  1092. return formatValue(row[columns[0]])
  1093. }
  1094. // Multi-column index: concatenate values with separator
  1095. var parts []string
  1096. for _, col := range columns {
  1097. parts = append(parts, formatValue(row[col]))
  1098. }
  1099. return strings.Join(parts, "\x00")
  1100. }
  1101. // SelectByIndex retrieves rows using an index lookup. It obtains the matching
  1102. // rowids from the in-memory index, then streams the table's rows and returns
  1103. // only those whose rowid is indexed, without retaining a permanent row map.
  1104. func (m *TableManager) SelectByIndex(table, indexName string, colValue interface{}) ([]Row, error) {
  1105. index, err := m.schema.GetIndex(indexName)
  1106. if err != nil {
  1107. return nil, err
  1108. }
  1109. if err := m.ensureIndex(index); err != nil {
  1110. return nil, err
  1111. }
  1112. tableKey := strings.ToLower(table)
  1113. tl := m.tableLock(tableKey)
  1114. tl.RLock()
  1115. defer tl.RUnlock()
  1116. if !m.schema.TableExists(table) {
  1117. return nil, fmt.Errorf("table not found: %s", table)
  1118. }
  1119. indexKey := strings.ToLower(indexName)
  1120. valueKey := formatIndexValue(colValue)
  1121. m.cacheMu.RLock()
  1122. rowids := append([]int64(nil), m.indexCache[indexKey][valueKey]...)
  1123. primaryKeys := make([]string, 0, len(rowids))
  1124. missingRowID := int64(0)
  1125. missingRowKey := false
  1126. for _, rowid := range rowids {
  1127. if primaryKey, ok := m.rowKeyCache[tableKey][rowid]; ok {
  1128. primaryKeys = append(primaryKeys, primaryKey)
  1129. } else {
  1130. missingRowID = rowid
  1131. missingRowKey = true
  1132. break
  1133. }
  1134. }
  1135. m.cacheMu.RUnlock()
  1136. if missingRowKey {
  1137. return nil, fmt.Errorf("index %s is missing rowid %d", indexName, missingRowID)
  1138. }
  1139. // If no rowids found, return empty result
  1140. if len(rowids) == 0 {
  1141. return []Row{}, nil
  1142. }
  1143. rows := make([]Row, 0, len(primaryKeys))
  1144. err = m.pool.WithClient(func(client *KVClient) error {
  1145. for _, primaryKey := range primaryKeys {
  1146. result, err := client.Get([]byte(m.dataKey(table, primaryKey)))
  1147. if err == ErrKeyNotFound {
  1148. return fmt.Errorf("index %s references missing primary key %s", indexName, primaryKey)
  1149. }
  1150. if err != nil {
  1151. return err
  1152. }
  1153. row, err := decodeRow(result.Value)
  1154. if err != nil {
  1155. return err
  1156. }
  1157. rows = append(rows, row)
  1158. }
  1159. return nil
  1160. })
  1161. if err != nil {
  1162. return nil, err
  1163. }
  1164. return rows, nil
  1165. }