2
0

table.go 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384
  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. // UpdateByPK updates one row without scanning the table.
  753. func (m *TableManager) UpdateByPK(table, pk string, updateFn func(Row) (Row, error)) (Row, bool, error) {
  754. tl := m.tableLock(table)
  755. tl.Lock()
  756. defer tl.Unlock()
  757. schema, err := m.schema.GetSchema(table)
  758. if err != nil {
  759. return nil, false, err
  760. }
  761. row, err := m.getByPKUnlocked(table, pk)
  762. if err == ErrKeyNotFound {
  763. return nil, false, nil
  764. }
  765. if err != nil {
  766. return nil, false, err
  767. }
  768. oldRow := cloneRow(row)
  769. m.updateIndexesForRow(table, oldRow, false)
  770. updates, err := updateFn(row)
  771. if err != nil {
  772. m.updateIndexesForRow(table, oldRow, true)
  773. return nil, false, err
  774. }
  775. for name, value := range updates {
  776. for _, column := range schema.Columns {
  777. if strings.EqualFold(name, column.Name) {
  778. row[column.Name] = value
  779. break
  780. }
  781. }
  782. }
  783. data, err := encodeRow(row)
  784. if err != nil {
  785. m.updateIndexesForRow(table, oldRow, true)
  786. return nil, false, err
  787. }
  788. err = m.pool.WithClient(func(client *KVClient) error {
  789. _, err := client.Put([]byte(m.dataKey(table, pk)), data)
  790. return err
  791. })
  792. if err != nil {
  793. m.updateIndexesForRow(table, oldRow, true)
  794. return nil, false, err
  795. }
  796. m.updateIndexesForRow(table, row, true)
  797. return oldRow, true, nil
  798. }
  799. // Delete deletes rows matching the filter.
  800. func (m *TableManager) Delete(table string, filter func(Row) bool) (int, error) {
  801. // Get all rows
  802. rows, err := m.Select(table, filter)
  803. if err != nil {
  804. return 0, err
  805. }
  806. tl := m.tableLock(strings.ToLower(table))
  807. tl.Lock()
  808. defer tl.Unlock()
  809. schema, err := m.schema.GetSchema(table)
  810. if err != nil {
  811. return 0, err
  812. }
  813. count := 0
  814. for _, row := range rows {
  815. // Remove index entries before deleting row
  816. m.updateIndexesForRow(table, row, false)
  817. pkValue := row[schema.PrimaryKey]
  818. pk := fmt.Sprintf("%v", pkValue)
  819. key := m.dataKey(table, pk)
  820. err = m.pool.WithClient(func(c *KVClient) error {
  821. _, err := c.Del([]byte(key))
  822. return err
  823. })
  824. if err == nil {
  825. count++
  826. } else {
  827. // Restore the index entries removed above.
  828. m.updateIndexesForRow(table, row, true)
  829. }
  830. }
  831. m.incrCount(table, schema.CreatedAt, -count)
  832. return count, nil
  833. }
  834. // DeleteByPK deletes one row without scanning the table.
  835. func (m *TableManager) DeleteByPK(table, pk string) (Row, bool, error) {
  836. tl := m.tableLock(table)
  837. tl.Lock()
  838. defer tl.Unlock()
  839. schema, err := m.schema.GetSchema(table)
  840. if err != nil {
  841. return nil, false, err
  842. }
  843. row, err := m.getByPKUnlocked(table, pk)
  844. if err == ErrKeyNotFound {
  845. return nil, false, nil
  846. }
  847. if err != nil {
  848. return nil, false, err
  849. }
  850. m.updateIndexesForRow(table, row, false)
  851. err = m.pool.WithClient(func(client *KVClient) error {
  852. _, err := client.Del([]byte(m.dataKey(table, pk)))
  853. return err
  854. })
  855. if err != nil {
  856. m.updateIndexesForRow(table, row, true)
  857. return nil, false, err
  858. }
  859. m.incrCount(table, schema.CreatedAt, -1)
  860. return row, true, nil
  861. }
  862. // GetByPK retrieves a row by primary key.
  863. func (m *TableManager) GetByPK(table string, pk string) (Row, error) {
  864. tl := m.tableLock(table)
  865. tl.RLock()
  866. defer tl.RUnlock()
  867. if !m.schema.TableExists(table) {
  868. return nil, fmt.Errorf("table not found: %s", table)
  869. }
  870. return m.getByPKUnlocked(table, pk)
  871. }
  872. func (m *TableManager) getByPKUnlocked(table, pk string) (Row, error) {
  873. key := m.dataKey(table, pk)
  874. var value []byte
  875. err := m.pool.WithClient(func(c *KVClient) error {
  876. res, err := c.Get([]byte(key))
  877. if err != nil {
  878. return err
  879. }
  880. value = res.Value
  881. return nil
  882. })
  883. if err != nil {
  884. return nil, err
  885. }
  886. row, err := decodeRow(value)
  887. if err != nil {
  888. return nil, fmt.Errorf("failed to parse row: %w", err)
  889. }
  890. return row, nil
  891. }
  892. // Count returns the number of rows in a table matching the filter.
  893. func (m *TableManager) Count(table string, filter func(Row) bool) (int, error) {
  894. tl := m.tableLock(table)
  895. tl.RLock()
  896. defer tl.RUnlock()
  897. if !m.schema.TableExists(table) {
  898. return 0, fmt.Errorf("table not found: %s", table)
  899. }
  900. count := 0
  901. err := m.scanRows(table, func(row Row) (bool, error) {
  902. if filter == nil || filter(row) {
  903. count++
  904. }
  905. return false, nil
  906. })
  907. if err != nil {
  908. return 0, err
  909. }
  910. return count, nil
  911. }
  912. // Truncate removes all rows from a table.
  913. func (m *TableManager) Truncate(table string) (int, error) {
  914. return m.Delete(table, nil)
  915. }
  916. // isIntegerType checks if a type name is an integer type.
  917. func isIntegerType(typeName string) bool {
  918. t := strings.ToUpper(typeName)
  919. switch t {
  920. case "INTEGER", "INT", "SMALLINT", "BIGINT", "TINYINT", "MEDIUMINT":
  921. return true
  922. }
  923. return false
  924. }
  925. // IsRowIDColumn checks if a column name is a ROWID alias.
  926. func IsRowIDColumn(name string) bool {
  927. n := strings.ToLower(name)
  928. return n == "rowid" || n == "oid" || n == "_rowid_"
  929. }
  930. // Index entry methods - leveraging radix trie for prefix-based lookups
  931. // Format: {database}:idx:{index_name}:{column_value} → JSON array of rowids
  932. // indexEntryKey returns the key for an index entry.
  933. func (m *TableManager) indexEntryKey(indexName string, colValue interface{}) string {
  934. return fmt.Sprintf("%s:idx:%s:%s", m.database, strings.ToLower(indexName), formatIndexValue(colValue))
  935. }
  936. // indexPrefix returns the prefix for all entries of an index.
  937. func (m *TableManager) indexPrefix(indexName string) string {
  938. return fmt.Sprintf("%s:idx:%s:", m.database, strings.ToLower(indexName))
  939. }
  940. func formatIndexValue(value interface{}) string {
  941. switch v := value.(type) {
  942. case float64:
  943. if v == float64(int64(v)) {
  944. return fmt.Sprintf("%d", int64(v))
  945. }
  946. return fmt.Sprintf("%f", v)
  947. case int64:
  948. return fmt.Sprintf("%d", v)
  949. case int:
  950. return fmt.Sprintf("%d", v)
  951. default:
  952. return fmt.Sprintf("%v", v)
  953. }
  954. }
  955. func rowIDFromRow(row Row) (int64, bool) {
  956. switch v := row["_rowid_"].(type) {
  957. case int64:
  958. return v, true
  959. case int:
  960. return int64(v), true
  961. case float64:
  962. return int64(v), true
  963. default:
  964. return 0, false
  965. }
  966. }
  967. func (m *TableManager) ensureIndex(index *Index) error {
  968. indexKey := strings.ToLower(index.Name)
  969. m.cacheMu.RLock()
  970. disabled := m.disabledIndexes[indexKey]
  971. _, initialized := m.indexCache[indexKey]
  972. m.cacheMu.RUnlock()
  973. if disabled {
  974. return nil
  975. }
  976. if initialized {
  977. return nil
  978. }
  979. // Serialize index build against writes to the same table so the derived
  980. // entries cannot miss a concurrently-inserted row.
  981. table := index.Table
  982. key := strings.ToLower(table)
  983. tl := m.tableLock(key)
  984. tl.Lock()
  985. defer tl.Unlock()
  986. m.cacheMu.RLock()
  987. disabled = m.disabledIndexes[indexKey]
  988. _, initialized = m.indexCache[indexKey]
  989. m.cacheMu.RUnlock()
  990. if disabled {
  991. return nil
  992. }
  993. if initialized {
  994. return nil
  995. }
  996. columns := make([]string, len(index.Columns))
  997. for i, col := range index.Columns {
  998. columns[i] = col.Name
  999. }
  1000. tableSchema, err := m.schema.GetSchema(table)
  1001. if err != nil {
  1002. return err
  1003. }
  1004. values := make(map[string][]int64)
  1005. rowKeys := make(map[int64]string)
  1006. if err := m.scanRows(table, func(row Row) (bool, error) {
  1007. rowid, ok := rowIDFromRow(row)
  1008. if !ok {
  1009. return false, nil
  1010. }
  1011. colValue := m.buildIndexValue(row, columns)
  1012. valueKey := formatIndexValue(colValue)
  1013. values[valueKey] = append(values[valueKey], rowid)
  1014. rowKeys[rowid] = fmt.Sprintf("%v", row[tableSchema.PrimaryKey])
  1015. return false, nil
  1016. }); err != nil {
  1017. return err
  1018. }
  1019. m.cacheMu.Lock()
  1020. if _, initialized := m.indexCache[indexKey]; !initialized {
  1021. m.indexCache[indexKey] = values
  1022. m.indexTable[indexKey] = key
  1023. m.rowKeyCache[key] = rowKeys
  1024. }
  1025. m.cacheMu.Unlock()
  1026. return nil
  1027. }
  1028. // AddIndexEntry adds a rowid to an in-memory index entry.
  1029. func (m *TableManager) AddIndexEntry(indexName string, colValue interface{}, rowid int64) error {
  1030. indexKey := strings.ToLower(indexName)
  1031. valueKey := formatIndexValue(colValue)
  1032. m.cacheMu.Lock()
  1033. defer m.cacheMu.Unlock()
  1034. values, ok := m.indexCache[indexKey]
  1035. if !ok {
  1036. return nil
  1037. }
  1038. rowids := values[valueKey]
  1039. for _, r := range rowids {
  1040. if r == rowid {
  1041. return nil
  1042. }
  1043. }
  1044. values[valueKey] = append(rowids, rowid)
  1045. return nil
  1046. }
  1047. // RemoveIndexEntry removes a rowid from an in-memory index entry.
  1048. func (m *TableManager) RemoveIndexEntry(indexName string, colValue interface{}, rowid int64) error {
  1049. indexKey := strings.ToLower(indexName)
  1050. valueKey := formatIndexValue(colValue)
  1051. m.cacheMu.Lock()
  1052. defer m.cacheMu.Unlock()
  1053. values, ok := m.indexCache[indexKey]
  1054. if !ok {
  1055. return nil
  1056. }
  1057. rowids := values[valueKey]
  1058. newRowids := make([]int64, 0, len(rowids))
  1059. for _, r := range rowids {
  1060. if r != rowid {
  1061. newRowids = append(newRowids, r)
  1062. }
  1063. }
  1064. if len(newRowids) == 0 {
  1065. delete(values, valueKey)
  1066. return nil
  1067. }
  1068. values[valueKey] = newRowids
  1069. return nil
  1070. }
  1071. // LookupIndex returns rowids matching a column value using the index.
  1072. func (m *TableManager) LookupIndex(indexName string, colValue interface{}) ([]int64, error) {
  1073. index, err := m.schema.GetIndex(indexName)
  1074. if err != nil {
  1075. return nil, err
  1076. }
  1077. if err := m.ensureIndex(index); err != nil {
  1078. return nil, err
  1079. }
  1080. indexKey := strings.ToLower(indexName)
  1081. valueKey := formatIndexValue(colValue)
  1082. m.cacheMu.RLock()
  1083. rowids := append([]int64(nil), m.indexCache[indexKey][valueKey]...)
  1084. m.cacheMu.RUnlock()
  1085. return rowids, nil
  1086. }
  1087. // ClearIndex removes an index's in-memory entries and marks it disabled so a
  1088. // concurrent lookup cannot rebuild it after DROP but before the schema entry
  1089. // is removed. Index entries are derived from durable rows, so there is nothing
  1090. // durable to delete here.
  1091. func (m *TableManager) ClearIndex(indexName, tableName string, columns []string) error {
  1092. indexKey := strings.ToLower(indexName)
  1093. tableKey := strings.ToLower(tableName)
  1094. m.cacheMu.Lock()
  1095. delete(m.indexCache, indexKey)
  1096. delete(m.indexTable, indexKey)
  1097. m.disabledIndexes[indexKey] = true
  1098. rowKeysNeeded := false
  1099. for _, indexedTable := range m.indexTable {
  1100. if indexedTable == tableKey {
  1101. rowKeysNeeded = true
  1102. break
  1103. }
  1104. }
  1105. if !rowKeysNeeded {
  1106. delete(m.rowKeyCache, tableKey)
  1107. }
  1108. m.cacheMu.Unlock()
  1109. return nil
  1110. }
  1111. // BuildIndex builds index entries for all existing rows in a table.
  1112. func (m *TableManager) BuildIndex(indexName, tableName string, columns []string) error {
  1113. indexKey := strings.ToLower(indexName)
  1114. m.cacheMu.Lock()
  1115. delete(m.disabledIndexes, indexKey)
  1116. delete(m.indexCache, indexKey)
  1117. delete(m.indexTable, indexKey)
  1118. m.cacheMu.Unlock()
  1119. index, err := m.schema.GetIndex(indexName)
  1120. if err == nil {
  1121. return m.ensureIndex(index)
  1122. }
  1123. tableSchema, schemaErr := m.schema.GetSchema(tableName)
  1124. if schemaErr != nil {
  1125. return schemaErr
  1126. }
  1127. values := make(map[string][]int64)
  1128. rowKeys := make(map[int64]string)
  1129. if err := m.scanRows(tableName, func(row Row) (bool, error) {
  1130. rowid, ok := rowIDFromRow(row)
  1131. if !ok {
  1132. return false, nil
  1133. }
  1134. colValue := m.buildIndexValue(row, columns)
  1135. values[formatIndexValue(colValue)] = append(values[formatIndexValue(colValue)], rowid)
  1136. rowKeys[rowid] = fmt.Sprintf("%v", row[tableSchema.PrimaryKey])
  1137. return false, nil
  1138. }); err != nil {
  1139. return err
  1140. }
  1141. m.cacheMu.Lock()
  1142. m.indexCache[indexKey] = values
  1143. m.indexTable[indexKey] = strings.ToLower(tableName)
  1144. m.rowKeyCache[strings.ToLower(tableName)] = rowKeys
  1145. m.cacheMu.Unlock()
  1146. return nil
  1147. }
  1148. // buildIndexValue creates the index key value from row columns.
  1149. func (m *TableManager) buildIndexValue(row Row, columns []string) string {
  1150. formatValue := func(v interface{}) string {
  1151. switch val := v.(type) {
  1152. case float64:
  1153. // Check if it's actually an integer value
  1154. if val == float64(int64(val)) {
  1155. return fmt.Sprintf("%d", int64(val))
  1156. }
  1157. return fmt.Sprintf("%f", val)
  1158. case int64:
  1159. return fmt.Sprintf("%d", val)
  1160. case int:
  1161. return fmt.Sprintf("%d", val)
  1162. default:
  1163. return fmt.Sprintf("%v", val)
  1164. }
  1165. }
  1166. if len(columns) == 1 {
  1167. return formatValue(row[columns[0]])
  1168. }
  1169. // Multi-column index: concatenate values with separator
  1170. var parts []string
  1171. for _, col := range columns {
  1172. parts = append(parts, formatValue(row[col]))
  1173. }
  1174. return strings.Join(parts, "\x00")
  1175. }
  1176. // SelectByIndex retrieves rows using an index lookup. It obtains the matching
  1177. // rowids from the in-memory index, then streams the table's rows and returns
  1178. // only those whose rowid is indexed, without retaining a permanent row map.
  1179. func (m *TableManager) SelectByIndex(table, indexName string, colValue interface{}) ([]Row, error) {
  1180. index, err := m.schema.GetIndex(indexName)
  1181. if err != nil {
  1182. return nil, err
  1183. }
  1184. if err := m.ensureIndex(index); err != nil {
  1185. return nil, err
  1186. }
  1187. tableKey := strings.ToLower(table)
  1188. tl := m.tableLock(tableKey)
  1189. tl.RLock()
  1190. defer tl.RUnlock()
  1191. if !m.schema.TableExists(table) {
  1192. return nil, fmt.Errorf("table not found: %s", table)
  1193. }
  1194. indexKey := strings.ToLower(indexName)
  1195. valueKey := formatIndexValue(colValue)
  1196. m.cacheMu.RLock()
  1197. rowids := append([]int64(nil), m.indexCache[indexKey][valueKey]...)
  1198. primaryKeys := make([]string, 0, len(rowids))
  1199. missingRowID := int64(0)
  1200. missingRowKey := false
  1201. for _, rowid := range rowids {
  1202. if primaryKey, ok := m.rowKeyCache[tableKey][rowid]; ok {
  1203. primaryKeys = append(primaryKeys, primaryKey)
  1204. } else {
  1205. missingRowID = rowid
  1206. missingRowKey = true
  1207. break
  1208. }
  1209. }
  1210. m.cacheMu.RUnlock()
  1211. if missingRowKey {
  1212. return nil, fmt.Errorf("index %s is missing rowid %d", indexName, missingRowID)
  1213. }
  1214. // If no rowids found, return empty result
  1215. if len(rowids) == 0 {
  1216. return []Row{}, nil
  1217. }
  1218. rows := make([]Row, 0, len(primaryKeys))
  1219. err = m.pool.WithClient(func(client *KVClient) error {
  1220. keys := make([][]byte, len(primaryKeys))
  1221. for i, primaryKey := range primaryKeys {
  1222. keys[i] = []byte(m.dataKey(table, primaryKey))
  1223. }
  1224. results, err := client.MultiGet(keys)
  1225. if err != nil {
  1226. return err
  1227. }
  1228. for i, result := range results {
  1229. if !result.Found {
  1230. primaryKey := primaryKeys[i]
  1231. return fmt.Errorf("index %s references missing primary key %s", indexName, primaryKey)
  1232. }
  1233. row, err := decodeRow(result.Value)
  1234. if err != nil {
  1235. return err
  1236. }
  1237. rows = append(rows, row)
  1238. }
  1239. return nil
  1240. })
  1241. if err != nil {
  1242. return nil, err
  1243. }
  1244. return rows, nil
  1245. }