table.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  1. package storage
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "strings"
  6. "sync"
  7. )
  8. // Row represents a database row.
  9. type Row map[string]interface{}
  10. // TableManager manages table data operations.
  11. type TableManager struct {
  12. pool *KVPool
  13. schema *SchemaManager
  14. database string
  15. cacheMu sync.RWMutex
  16. rowCache map[string][]Row // table name → all rows (nil means not loaded)
  17. }
  18. // NewTableManager creates a new table manager.
  19. func NewTableManager(pool *KVPool, schema *SchemaManager, database string) *TableManager {
  20. return &TableManager{
  21. pool: pool,
  22. schema: schema,
  23. database: database,
  24. rowCache: make(map[string][]Row),
  25. }
  26. }
  27. // invalidateCache removes a table's rows from the in-memory cache.
  28. func (m *TableManager) invalidateCache(table string) {
  29. m.cacheMu.Lock()
  30. delete(m.rowCache, strings.ToLower(table))
  31. m.cacheMu.Unlock()
  32. }
  33. // InvalidateCache is the exported version for use by the executor.
  34. func (m *TableManager) InvalidateCache(table string) {
  35. m.invalidateCache(table)
  36. }
  37. // dataKey returns the key for a row.
  38. func (m *TableManager) dataKey(table, pk string) string {
  39. return fmt.Sprintf("%s:_data:%s:%s", m.database, strings.ToLower(table), pk)
  40. }
  41. // dataPrefix returns the prefix for all rows in a table.
  42. func (m *TableManager) dataPrefix(table string) string {
  43. return fmt.Sprintf("%s:_data:%s:", m.database, strings.ToLower(table))
  44. }
  45. // Insert inserts a new row.
  46. func (m *TableManager) Insert(table string, row Row) error {
  47. schema, err := m.schema.GetSchema(table)
  48. if err != nil {
  49. return err
  50. }
  51. // Get primary key value
  52. pkValue, ok := row[schema.PrimaryKey]
  53. if !ok {
  54. // Try case-insensitive lookup
  55. for k, v := range row {
  56. if strings.EqualFold(k, schema.PrimaryKey) {
  57. pkValue = v
  58. ok = true
  59. break
  60. }
  61. }
  62. }
  63. // Check if PK is INTEGER PRIMARY KEY (implicit ROWID alias)
  64. pkCol, _ := schema.GetColumn(schema.PrimaryKey)
  65. isIntegerPK := pkCol != nil && isIntegerType(pkCol.Type)
  66. // Auto-generate ROWID if no primary key provided or if it's INTEGER PRIMARY KEY
  67. var rowid int64
  68. if !ok || pkValue == nil {
  69. if isIntegerPK || !ok {
  70. // Generate ROWID
  71. rowid, err = m.schema.GetNextRowID(table)
  72. if err != nil {
  73. return err
  74. }
  75. pkValue = rowid
  76. row[schema.PrimaryKey] = rowid
  77. ok = true
  78. } else {
  79. return fmt.Errorf("missing primary key: %s", schema.PrimaryKey)
  80. }
  81. } else if isIntegerPK {
  82. // User provided INTEGER PRIMARY KEY value - track it
  83. switch v := pkValue.(type) {
  84. case int64:
  85. rowid = v
  86. case float64:
  87. rowid = int64(v)
  88. case int:
  89. rowid = int64(v)
  90. default:
  91. rowid = 0
  92. }
  93. if rowid > 0 {
  94. m.schema.UpdateMaxRowID(table, rowid)
  95. }
  96. }
  97. pk := fmt.Sprintf("%v", pkValue)
  98. // Check for duplicate
  99. key := m.dataKey(table, pk)
  100. err = m.pool.WithClient(func(c *KVClient) error {
  101. _, err := c.Read(key)
  102. return err
  103. })
  104. if err == nil {
  105. return fmt.Errorf("duplicate primary key: %s", pk)
  106. }
  107. // Validate required columns
  108. for _, col := range schema.Columns {
  109. if !col.Nullable && col.Default == nil {
  110. val, hasVal := row[col.Name]
  111. if !hasVal {
  112. // Try case-insensitive lookup
  113. for k, v := range row {
  114. if strings.EqualFold(k, col.Name) {
  115. val = v
  116. hasVal = true
  117. break
  118. }
  119. }
  120. }
  121. if !hasVal || val == nil {
  122. return fmt.Errorf("missing required column: %s", col.Name)
  123. }
  124. }
  125. }
  126. // Normalize column names to match schema
  127. normalizedRow := make(Row)
  128. for _, col := range schema.Columns {
  129. for k, v := range row {
  130. if strings.EqualFold(k, col.Name) {
  131. normalizedRow[col.Name] = v
  132. break
  133. }
  134. }
  135. }
  136. // Apply defaults
  137. for _, col := range schema.Columns {
  138. if _, ok := normalizedRow[col.Name]; !ok && col.Default != nil {
  139. normalizedRow[col.Name] = col.Default
  140. }
  141. }
  142. // Store ROWID (use PK value for INTEGER PRIMARY KEY, otherwise generate)
  143. if rowid > 0 {
  144. normalizedRow["_rowid_"] = rowid
  145. } else {
  146. // Generate ROWID for non-integer primary keys
  147. newRowID, _ := m.schema.GetNextRowID(table)
  148. normalizedRow["_rowid_"] = newRowID
  149. }
  150. // Serialize row
  151. data, err := json.Marshal(normalizedRow)
  152. if err != nil {
  153. return fmt.Errorf("failed to serialize row: %w", err)
  154. }
  155. // Write row
  156. err = m.pool.WithClient(func(c *KVClient) error {
  157. return c.Write(key, string(data))
  158. })
  159. if err != nil {
  160. return err
  161. }
  162. // Update indexes
  163. m.updateIndexesForRow(table, normalizedRow, true)
  164. m.invalidateCache(table)
  165. return nil
  166. }
  167. // InsertBulk inserts multiple rows efficiently, parallelizing KV writes across
  168. // the connection pool. Skips per-row duplicate checks (caller must ensure
  169. // uniqueness). Used by INSERT ... SELECT.
  170. func (m *TableManager) InsertBulk(table string, rows []Row) (int, error) {
  171. if len(rows) == 0 {
  172. return 0, nil
  173. }
  174. schema, err := m.schema.GetSchema(table)
  175. if err != nil {
  176. return 0, err
  177. }
  178. pkCol, _ := schema.GetColumn(schema.PrimaryKey)
  179. isIntegerPK := pkCol != nil && isIntegerType(pkCol.Type)
  180. // Normalize rows and assign _rowid_.
  181. normalized := make([]Row, 0, len(rows))
  182. var maxRowID int64
  183. for _, row := range rows {
  184. nr := make(Row)
  185. for _, col := range schema.Columns {
  186. for k, v := range row {
  187. if strings.EqualFold(k, col.Name) {
  188. nr[col.Name] = v
  189. break
  190. }
  191. }
  192. }
  193. for _, col := range schema.Columns {
  194. if _, ok := nr[col.Name]; !ok && col.Default != nil {
  195. nr[col.Name] = col.Default
  196. }
  197. }
  198. var rowid int64
  199. var hasRowid bool
  200. if isIntegerPK {
  201. switch v := nr[schema.PrimaryKey].(type) {
  202. case float64:
  203. rowid = int64(v)
  204. hasRowid = true
  205. case int64:
  206. rowid = v
  207. hasRowid = true
  208. case int:
  209. rowid = int64(v)
  210. hasRowid = true
  211. }
  212. }
  213. if !hasRowid {
  214. // Fall back to sequential insert for non-integer-pk rows.
  215. if err := m.Insert(table, row); err != nil {
  216. return len(normalized), err
  217. }
  218. continue
  219. }
  220. nr["_rowid_"] = rowid
  221. if rowid > maxRowID {
  222. maxRowID = rowid
  223. }
  224. normalized = append(normalized, nr)
  225. }
  226. if maxRowID > 0 {
  227. m.schema.UpdateMaxRowID(table, maxRowID)
  228. }
  229. // Serialize all rows.
  230. type kv struct{ key, val string }
  231. rowKVs := make([]kv, 0, len(normalized))
  232. for _, nr := range normalized {
  233. pk := fmt.Sprintf("%v", nr[schema.PrimaryKey])
  234. data, err := json.Marshal(nr)
  235. if err != nil {
  236. return 0, err
  237. }
  238. rowKVs = append(rowKVs, kv{m.dataKey(table, pk), string(data)})
  239. }
  240. // Write rows concurrently.
  241. errs := make([]error, len(rowKVs))
  242. var wg sync.WaitGroup
  243. for i, w := range rowKVs {
  244. wg.Add(1)
  245. i, w := i, w
  246. go func() {
  247. defer wg.Done()
  248. errs[i] = m.pool.WithClient(func(c *KVClient) error {
  249. return c.Write(w.key, w.val)
  250. })
  251. }()
  252. }
  253. wg.Wait()
  254. for _, e := range errs {
  255. if e != nil {
  256. return 0, e
  257. }
  258. }
  259. // Build index entries grouped by key (to avoid read-merge races).
  260. indexes, _ := m.schema.ListTableIndexes(table)
  261. if len(indexes) > 0 {
  262. // For each index, gather {indexKey → []rowid} from the new rows.
  263. type indexEntry struct {
  264. key string
  265. rowids []int64
  266. }
  267. var entries []indexEntry
  268. for _, idx := range indexes {
  269. cols := make([]string, len(idx.Columns))
  270. for i, c := range idx.Columns {
  271. cols[i] = c.Name
  272. }
  273. byKey := make(map[string][]int64)
  274. for _, nr := range normalized {
  275. colVal := m.buildIndexValue(nr, cols)
  276. ikey := m.indexEntryKey(idx.Name, colVal)
  277. var rowid int64
  278. switch v := nr["_rowid_"].(type) {
  279. case int64:
  280. rowid = v
  281. case float64:
  282. rowid = int64(v)
  283. }
  284. byKey[ikey] = append(byKey[ikey], rowid)
  285. }
  286. for k, rs := range byKey {
  287. entries = append(entries, indexEntry{k, rs})
  288. }
  289. }
  290. // Write index entries concurrently; each key is handled by exactly
  291. // one goroutine so there's no merge race.
  292. ieErrs := make([]error, len(entries))
  293. var iwg sync.WaitGroup
  294. for i, e := range entries {
  295. iwg.Add(1)
  296. i, e := i, e
  297. go func() {
  298. defer iwg.Done()
  299. // Merge with any existing rowids for this key.
  300. var existing []int64
  301. m.pool.WithClient(func(c *KVClient) error {
  302. data, err := c.Read(e.key)
  303. if err == nil {
  304. json.Unmarshal([]byte(data), &existing)
  305. }
  306. return nil
  307. })
  308. merged := append(existing, e.rowids...)
  309. data, _ := json.Marshal(merged)
  310. ieErrs[i] = m.pool.WithClient(func(c *KVClient) error {
  311. return c.Write(e.key, string(data))
  312. })
  313. }()
  314. }
  315. iwg.Wait()
  316. for _, e := range ieErrs {
  317. if e != nil {
  318. return 0, e
  319. }
  320. }
  321. }
  322. m.invalidateCache(table)
  323. return len(normalized), nil
  324. }
  325. // updateIndexesForRow adds or removes index entries for a row.
  326. func (m *TableManager) updateIndexesForRow(table string, row Row, add bool) {
  327. indexes, err := m.schema.ListTableIndexes(table)
  328. if err != nil || len(indexes) == 0 {
  329. return
  330. }
  331. rowid, ok := row["_rowid_"].(float64)
  332. if !ok {
  333. if rid, ok := row["_rowid_"].(int64); ok {
  334. rowid = float64(rid)
  335. } else {
  336. return
  337. }
  338. }
  339. for _, idx := range indexes {
  340. columns := make([]string, len(idx.Columns))
  341. for i, col := range idx.Columns {
  342. columns[i] = col.Name
  343. }
  344. colValue := m.buildIndexValue(row, columns)
  345. if add {
  346. m.AddIndexEntry(idx.Name, colValue, int64(rowid))
  347. } else {
  348. m.RemoveIndexEntry(idx.Name, colValue, int64(rowid))
  349. }
  350. }
  351. }
  352. // Select retrieves rows from a table.
  353. func (m *TableManager) Select(table string, filter func(Row) bool) ([]Row, error) {
  354. if !m.schema.TableExists(table) {
  355. return nil, fmt.Errorf("table not found: %s", table)
  356. }
  357. key := strings.ToLower(table)
  358. m.cacheMu.RLock()
  359. cached, ok := m.rowCache[key]
  360. m.cacheMu.RUnlock()
  361. if !ok {
  362. prefix := m.dataPrefix(table)
  363. var values []string
  364. err := m.pool.WithClient(func(c *KVClient) error {
  365. var err error
  366. values, err = c.Reads(prefix)
  367. return err
  368. })
  369. if err != nil {
  370. return nil, err
  371. }
  372. loaded := make([]Row, 0, len(values))
  373. for _, data := range values {
  374. var row Row
  375. if err := json.Unmarshal([]byte(data), &row); err != nil {
  376. continue
  377. }
  378. loaded = append(loaded, row)
  379. }
  380. m.cacheMu.Lock()
  381. m.rowCache[key] = loaded
  382. m.cacheMu.Unlock()
  383. cached = loaded
  384. }
  385. if filter == nil {
  386. result := make([]Row, len(cached))
  387. copy(result, cached)
  388. return result, nil
  389. }
  390. rows := make([]Row, 0, len(cached))
  391. for _, row := range cached {
  392. if filter(row) {
  393. rows = append(rows, row)
  394. }
  395. }
  396. return rows, nil
  397. }
  398. // SelectWithLimit retrieves rows with limit and offset.
  399. func (m *TableManager) SelectWithLimit(table string, filter func(Row) bool, limit, offset int) ([]Row, error) {
  400. rows, err := m.Select(table, filter)
  401. if err != nil {
  402. return nil, err
  403. }
  404. // Apply offset
  405. if offset > 0 {
  406. if offset >= len(rows) {
  407. return nil, nil
  408. }
  409. rows = rows[offset:]
  410. }
  411. // Apply limit
  412. if limit > 0 && limit < len(rows) {
  413. rows = rows[:limit]
  414. }
  415. return rows, nil
  416. }
  417. // Update updates rows matching the filter.
  418. func (m *TableManager) Update(table string, updates Row, filter func(Row) bool) (int, error) {
  419. schema, err := m.schema.GetSchema(table)
  420. if err != nil {
  421. return 0, err
  422. }
  423. // Get all rows
  424. rows, err := m.Select(table, filter)
  425. if err != nil {
  426. return 0, err
  427. }
  428. count := 0
  429. for _, row := range rows {
  430. // Remove old index entries before update
  431. m.updateIndexesForRow(table, row, false)
  432. // Apply updates
  433. for k, v := range updates {
  434. // Normalize column name
  435. for _, col := range schema.Columns {
  436. if strings.EqualFold(k, col.Name) {
  437. row[col.Name] = v
  438. break
  439. }
  440. }
  441. }
  442. // Get primary key
  443. pkValue := row[schema.PrimaryKey]
  444. pk := fmt.Sprintf("%v", pkValue)
  445. // Serialize row
  446. data, err := json.Marshal(row)
  447. if err != nil {
  448. continue
  449. }
  450. // Write back
  451. key := m.dataKey(table, pk)
  452. err = m.pool.WithClient(func(c *KVClient) error {
  453. return c.Write(key, string(data))
  454. })
  455. if err == nil {
  456. // Add new index entries after update
  457. m.updateIndexesForRow(table, row, true)
  458. count++
  459. }
  460. }
  461. m.invalidateCache(table)
  462. return count, nil
  463. }
  464. // UpdateFunc updates rows matching the filter using a function to compute new values.
  465. // The updateFn receives the current row and returns the updates to apply.
  466. func (m *TableManager) UpdateFunc(table string, updateFn func(Row) (Row, error), filter func(Row) bool) (int, error) {
  467. schema, err := m.schema.GetSchema(table)
  468. if err != nil {
  469. return 0, err
  470. }
  471. // Get all rows
  472. rows, err := m.Select(table, filter)
  473. if err != nil {
  474. return 0, err
  475. }
  476. count := 0
  477. for _, row := range rows {
  478. // Remove old index entries before update
  479. m.updateIndexesForRow(table, row, false)
  480. // Compute updates using the provided function
  481. updates, err := updateFn(row)
  482. if err != nil {
  483. return count, err
  484. }
  485. // Apply updates
  486. for k, v := range updates {
  487. // Normalize column name
  488. for _, col := range schema.Columns {
  489. if strings.EqualFold(k, col.Name) {
  490. row[col.Name] = v
  491. break
  492. }
  493. }
  494. }
  495. // Get primary key
  496. pkValue := row[schema.PrimaryKey]
  497. pk := fmt.Sprintf("%v", pkValue)
  498. // Serialize row
  499. data, err := json.Marshal(row)
  500. if err != nil {
  501. continue
  502. }
  503. // Write back
  504. key := m.dataKey(table, pk)
  505. err = m.pool.WithClient(func(c *KVClient) error {
  506. return c.Write(key, string(data))
  507. })
  508. if err == nil {
  509. // Add new index entries after update
  510. m.updateIndexesForRow(table, row, true)
  511. count++
  512. }
  513. }
  514. m.invalidateCache(table)
  515. return count, nil
  516. }
  517. // Delete deletes rows matching the filter.
  518. func (m *TableManager) Delete(table string, filter func(Row) bool) (int, error) {
  519. schema, err := m.schema.GetSchema(table)
  520. if err != nil {
  521. return 0, err
  522. }
  523. // Get all rows
  524. rows, err := m.Select(table, filter)
  525. if err != nil {
  526. return 0, err
  527. }
  528. count := 0
  529. for _, row := range rows {
  530. // Remove index entries before deleting row
  531. m.updateIndexesForRow(table, row, false)
  532. pkValue := row[schema.PrimaryKey]
  533. pk := fmt.Sprintf("%v", pkValue)
  534. key := m.dataKey(table, pk)
  535. err = m.pool.WithClient(func(c *KVClient) error {
  536. return c.Delete(key)
  537. })
  538. if err == nil {
  539. count++
  540. }
  541. }
  542. m.invalidateCache(table)
  543. return count, nil
  544. }
  545. // GetByPK retrieves a row by primary key.
  546. func (m *TableManager) GetByPK(table string, pk string) (Row, error) {
  547. if !m.schema.TableExists(table) {
  548. return nil, fmt.Errorf("table not found: %s", table)
  549. }
  550. key := m.dataKey(table, pk)
  551. var data string
  552. err := m.pool.WithClient(func(c *KVClient) error {
  553. var err error
  554. data, err = c.Read(key)
  555. return err
  556. })
  557. if err != nil {
  558. if err == ErrKeyNotFound {
  559. return nil, fmt.Errorf("row not found: %s", pk)
  560. }
  561. return nil, err
  562. }
  563. var row Row
  564. if err := json.Unmarshal([]byte(data), &row); err != nil {
  565. return nil, fmt.Errorf("failed to parse row: %w", err)
  566. }
  567. return row, nil
  568. }
  569. // Count returns the number of rows in a table.
  570. func (m *TableManager) Count(table string, filter func(Row) bool) (int, error) {
  571. rows, err := m.Select(table, filter)
  572. if err != nil {
  573. return 0, err
  574. }
  575. return len(rows), nil
  576. }
  577. // Truncate removes all rows from a table.
  578. func (m *TableManager) Truncate(table string) (int, error) {
  579. return m.Delete(table, nil)
  580. }
  581. // isIntegerType checks if a type name is an integer type.
  582. func isIntegerType(typeName string) bool {
  583. t := strings.ToUpper(typeName)
  584. switch t {
  585. case "INTEGER", "INT", "SMALLINT", "BIGINT", "TINYINT", "MEDIUMINT":
  586. return true
  587. }
  588. return false
  589. }
  590. // IsRowIDColumn checks if a column name is a ROWID alias.
  591. func IsRowIDColumn(name string) bool {
  592. n := strings.ToLower(name)
  593. return n == "rowid" || n == "oid" || n == "_rowid_"
  594. }
  595. // Index entry methods - leveraging radix trie for prefix-based lookups
  596. // Format: {database}:idx:{index_name}:{column_value} → JSON array of rowids
  597. // indexEntryKey returns the key for an index entry.
  598. func (m *TableManager) indexEntryKey(indexName string, colValue interface{}) string {
  599. // Format the value without scientific notation
  600. var valueStr string
  601. switch v := colValue.(type) {
  602. case float64:
  603. // Check if it's actually an integer value
  604. if v == float64(int64(v)) {
  605. valueStr = fmt.Sprintf("%d", int64(v))
  606. } else {
  607. valueStr = fmt.Sprintf("%f", v)
  608. }
  609. case int64:
  610. valueStr = fmt.Sprintf("%d", v)
  611. case int:
  612. valueStr = fmt.Sprintf("%d", v)
  613. default:
  614. valueStr = fmt.Sprintf("%v", v)
  615. }
  616. return fmt.Sprintf("%s:idx:%s:%s", m.database, strings.ToLower(indexName), valueStr)
  617. }
  618. // indexPrefix returns the prefix for all entries of an index.
  619. func (m *TableManager) indexPrefix(indexName string) string {
  620. return fmt.Sprintf("%s:idx:%s:", m.database, strings.ToLower(indexName))
  621. }
  622. // AddIndexEntry adds a rowid to an index entry.
  623. func (m *TableManager) AddIndexEntry(indexName string, colValue interface{}, rowid int64) error {
  624. key := m.indexEntryKey(indexName, colValue)
  625. // Read existing rowids
  626. var rowids []int64
  627. err := m.pool.WithClient(func(c *KVClient) error {
  628. data, err := c.Read(key)
  629. if err == nil && data != "" {
  630. json.Unmarshal([]byte(data), &rowids)
  631. }
  632. return nil // Ignore not found errors
  633. })
  634. if err != nil {
  635. return err
  636. }
  637. // Add new rowid if not already present
  638. for _, r := range rowids {
  639. if r == rowid {
  640. return nil // Already exists
  641. }
  642. }
  643. rowids = append(rowids, rowid)
  644. // Write back
  645. data, _ := json.Marshal(rowids)
  646. return m.pool.WithClient(func(c *KVClient) error {
  647. return c.Write(key, string(data))
  648. })
  649. }
  650. // RemoveIndexEntry removes a rowid from an index entry.
  651. func (m *TableManager) RemoveIndexEntry(indexName string, colValue interface{}, rowid int64) error {
  652. key := m.indexEntryKey(indexName, colValue)
  653. // Read existing rowids
  654. var rowids []int64
  655. err := m.pool.WithClient(func(c *KVClient) error {
  656. data, err := c.Read(key)
  657. if err != nil {
  658. return err
  659. }
  660. json.Unmarshal([]byte(data), &rowids)
  661. return nil
  662. })
  663. if err != nil {
  664. return nil // Entry doesn't exist
  665. }
  666. // Remove rowid
  667. newRowids := make([]int64, 0, len(rowids))
  668. for _, r := range rowids {
  669. if r != rowid {
  670. newRowids = append(newRowids, r)
  671. }
  672. }
  673. if len(newRowids) == 0 {
  674. // Delete the entry entirely
  675. return m.pool.WithClient(func(c *KVClient) error {
  676. return c.Delete(key)
  677. })
  678. }
  679. // Write back
  680. data, _ := json.Marshal(newRowids)
  681. return m.pool.WithClient(func(c *KVClient) error {
  682. return c.Write(key, string(data))
  683. })
  684. }
  685. // LookupIndex returns rowids matching a column value using the index.
  686. func (m *TableManager) LookupIndex(indexName string, colValue interface{}) ([]int64, error) {
  687. key := m.indexEntryKey(indexName, colValue)
  688. var rowids []int64
  689. err := m.pool.WithClient(func(c *KVClient) error {
  690. data, err := c.Read(key)
  691. if err != nil {
  692. return err
  693. }
  694. return json.Unmarshal([]byte(data), &rowids)
  695. })
  696. if err != nil {
  697. return nil, nil // Return empty if not found
  698. }
  699. return rowids, nil
  700. }
  701. // ClearIndex removes all entries for an index by scanning table and removing entries.
  702. func (m *TableManager) ClearIndex(indexName, tableName string, columns []string) error {
  703. rows, err := m.Select(tableName, nil)
  704. if err != nil {
  705. return err
  706. }
  707. for _, row := range rows {
  708. colValue := m.buildIndexValue(row, columns)
  709. key := m.indexEntryKey(indexName, colValue)
  710. m.pool.WithClient(func(c *KVClient) error {
  711. return c.Delete(key)
  712. })
  713. }
  714. return nil
  715. }
  716. // BuildIndex builds index entries for all existing rows in a table.
  717. func (m *TableManager) BuildIndex(indexName, tableName string, columns []string) error {
  718. rows, err := m.Select(tableName, nil)
  719. if err != nil {
  720. return err
  721. }
  722. for _, row := range rows {
  723. rowid, ok := row["_rowid_"].(float64)
  724. if !ok {
  725. continue
  726. }
  727. // Build composite key value for multi-column indexes
  728. colValue := m.buildIndexValue(row, columns)
  729. if err := m.AddIndexEntry(indexName, colValue, int64(rowid)); err != nil {
  730. return err
  731. }
  732. }
  733. return nil
  734. }
  735. // buildIndexValue creates the index key value from row columns.
  736. func (m *TableManager) buildIndexValue(row Row, columns []string) string {
  737. formatValue := func(v interface{}) string {
  738. switch val := v.(type) {
  739. case float64:
  740. // Check if it's actually an integer value
  741. if val == float64(int64(val)) {
  742. return fmt.Sprintf("%d", int64(val))
  743. }
  744. return fmt.Sprintf("%f", val)
  745. case int64:
  746. return fmt.Sprintf("%d", val)
  747. case int:
  748. return fmt.Sprintf("%d", val)
  749. default:
  750. return fmt.Sprintf("%v", val)
  751. }
  752. }
  753. if len(columns) == 1 {
  754. return formatValue(row[columns[0]])
  755. }
  756. // Multi-column index: concatenate values with separator
  757. var parts []string
  758. for _, col := range columns {
  759. parts = append(parts, formatValue(row[col]))
  760. }
  761. return strings.Join(parts, "\x00")
  762. }
  763. // SelectByIndex retrieves rows using an index lookup.
  764. func (m *TableManager) SelectByIndex(table, indexName string, colValue interface{}) ([]Row, error) {
  765. rowids, err := m.LookupIndex(indexName, colValue)
  766. if err != nil {
  767. return nil, err
  768. }
  769. // If no rowids found, return empty result
  770. if len(rowids) == 0 {
  771. return []Row{}, nil
  772. }
  773. // Build a set of target rowids for O(1) lookup.
  774. rowidSet := make(map[int64]struct{}, len(rowids))
  775. for _, rid := range rowids {
  776. rowidSet[rid] = struct{}{}
  777. }
  778. allRows, _ := m.Select(table, func(r Row) bool {
  779. switch v := r["_rowid_"].(type) {
  780. case float64:
  781. _, ok := rowidSet[int64(v)]
  782. return ok
  783. case int64:
  784. _, ok := rowidSet[v]
  785. return ok
  786. }
  787. return false
  788. })
  789. rows := allRows
  790. return rows, nil
  791. }