table.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194
  1. package storage
  2. import (
  3. "fmt"
  4. "strings"
  5. "sync"
  6. "github.com/goccy/go-json"
  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. rowIDMap map[string]map[int64]Row
  18. indexCache map[string]map[string][]int64 // index name → indexed value → rowids
  19. indexTable map[string]string // index name → table name
  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. // locks is a map of per-table mutexes used to serialize cache/count/index
  29. // loading (KV scan + install) against writes to the same table, so a scan
  30. // cannot miss or double-count a concurrent write. Operations on different
  31. // tables proceed concurrently. locksMu guards only the map itself and is
  32. // never held across I/O or row operations.
  33. locksMu sync.Mutex
  34. locks map[string]*sync.Mutex
  35. }
  36. // NewTableManager creates a new table manager.
  37. func NewTableManager(pool *KVPool, schema *SchemaManager, database string) *TableManager {
  38. return &TableManager{
  39. pool: pool,
  40. schema: schema,
  41. database: database,
  42. rowCache: make(map[string][]Row),
  43. rowIDMap: make(map[string]map[int64]Row),
  44. indexCache: make(map[string]map[string][]int64),
  45. indexTable: make(map[string]string),
  46. disabledIndexes: make(map[string]bool),
  47. counts: make(map[string]int),
  48. countsInit: make(map[string]bool),
  49. locks: make(map[string]*sync.Mutex),
  50. }
  51. }
  52. // tableLock returns the per-table mutex keyed by lowercase table name.
  53. func (m *TableManager) tableLock(key string) *sync.Mutex {
  54. m.locksMu.Lock()
  55. l, ok := m.locks[key]
  56. if !ok {
  57. l = &sync.Mutex{}
  58. m.locks[key] = l
  59. }
  60. m.locksMu.Unlock()
  61. return l
  62. }
  63. // invalidateCache removes a table's rows from the in-memory cache.
  64. func (m *TableManager) invalidateCache(table string) {
  65. m.cacheMu.Lock()
  66. key := strings.ToLower(table)
  67. delete(m.rowCache, key)
  68. delete(m.rowIDMap, key)
  69. for indexName, tableName := range m.indexTable {
  70. if tableName == key {
  71. delete(m.indexCache, indexName)
  72. delete(m.indexTable, indexName)
  73. }
  74. }
  75. m.cacheMu.Unlock()
  76. }
  77. // InvalidateCache is the exported version for use by the executor.
  78. func (m *TableManager) InvalidateCache(table string) {
  79. m.invalidateCache(table)
  80. }
  81. // loadTableLocked ensures the row cache for key is populated from durable rows.
  82. // The caller must hold the table's per-table lock so a concurrent write cannot
  83. // slip between the KV scan and the cache install.
  84. func (m *TableManager) loadTableLocked(key, table string) error {
  85. m.cacheMu.RLock()
  86. _, ok := m.rowCache[key]
  87. m.cacheMu.RUnlock()
  88. if ok {
  89. return nil
  90. }
  91. prefix := m.dataPrefix(table)
  92. var values []string
  93. err := m.pool.WithClient(func(c *KVClient) error {
  94. var err error
  95. values, err = c.Reads(prefix)
  96. return err
  97. })
  98. if err != nil {
  99. return err
  100. }
  101. loaded := make([]Row, 0, len(values))
  102. byRowID := make(map[int64]Row, len(values))
  103. for _, data := range values {
  104. var row Row
  105. if err := json.Unmarshal([]byte(data), &row); err != nil {
  106. continue
  107. }
  108. loaded = append(loaded, row)
  109. if rowid, ok := valueAsInt64(row["_rowid_"]); ok {
  110. byRowID[rowid] = row
  111. }
  112. }
  113. m.cacheMu.Lock()
  114. if _, ok := m.rowCache[key]; !ok {
  115. m.rowCache[key] = loaded
  116. m.rowIDMap[key] = byRowID
  117. }
  118. m.cacheMu.Unlock()
  119. return nil
  120. }
  121. // loadTable populates the row cache for table, acquiring the per-table lock.
  122. func (m *TableManager) loadTable(key, table string) error {
  123. tl := m.tableLock(key)
  124. tl.Lock()
  125. defer tl.Unlock()
  126. return m.loadTableLocked(key, table)
  127. }
  128. // CountFast returns the exact number of rows in a table. The count is derived
  129. // from durable rows on first use (recovering across restarts) and then
  130. // maintained incrementally by the write paths, so repeated COUNT(*) queries
  131. // avoid a full table scan. It intentionally does not persist a counter to KV:
  132. // the KV layer has no atomic increment primitive, and a durable counter that
  133. // could diverge from the rows on crash would be worse than a lazily-derived,
  134. // always-exact value. The cost is one table scan the first time COUNT(*) is
  135. // issued after startup.
  136. func (m *TableManager) CountFast(table string) (int, error) {
  137. key := strings.ToLower(table)
  138. m.cacheMu.RLock()
  139. init := m.countsInit[key]
  140. n := m.counts[key]
  141. m.cacheMu.RUnlock()
  142. if init {
  143. return n, nil
  144. }
  145. // Serialize first-time derivation against writes to this table so a
  146. // concurrent insert/delete cannot be missed or double-counted.
  147. tl := m.tableLock(key)
  148. tl.Lock()
  149. defer tl.Unlock()
  150. m.cacheMu.RLock()
  151. init = m.countsInit[key]
  152. n = m.counts[key]
  153. m.cacheMu.RUnlock()
  154. if init {
  155. return n, nil
  156. }
  157. prefix := m.dataPrefix(table)
  158. var values []string
  159. err := m.pool.WithClient(func(c *KVClient) error {
  160. var err error
  161. values, err = c.Reads(prefix)
  162. return err
  163. })
  164. if err != nil {
  165. return 0, err
  166. }
  167. m.cacheMu.Lock()
  168. m.counts[key] = len(values)
  169. m.countsInit[key] = true
  170. m.cacheMu.Unlock()
  171. return len(values), nil
  172. }
  173. // incrCount adjusts the derived per-table row count. It is a no-op until the
  174. // count has been initialized, since an uninitialized count is re-derived from
  175. // durable rows (which already reflect the write) on next use.
  176. func (m *TableManager) incrCount(table string, delta int) {
  177. key := strings.ToLower(table)
  178. m.cacheMu.Lock()
  179. if m.countsInit[key] {
  180. m.counts[key] += delta
  181. }
  182. m.cacheMu.Unlock()
  183. }
  184. // cacheInsert adds a row to the in-memory row cache if it is already loaded.
  185. // It is idempotent: a rowid already present is not appended twice, so a
  186. // partially-observed bulk insert cannot duplicate cache entries.
  187. func (m *TableManager) cacheInsert(table string, row Row) {
  188. key := strings.ToLower(table)
  189. rowid, ok := rowIDFromRow(row)
  190. m.cacheMu.Lock()
  191. defer m.cacheMu.Unlock()
  192. byRowID, loaded := m.rowIDMap[key]
  193. if !loaded {
  194. return
  195. }
  196. if ok {
  197. if _, exists := byRowID[rowid]; exists {
  198. return
  199. }
  200. byRowID[rowid] = row
  201. }
  202. m.rowCache[key] = append(m.rowCache[key], row)
  203. }
  204. // cacheDelete removes a row from the in-memory row cache if it is already loaded.
  205. func (m *TableManager) cacheDelete(table string, row Row) {
  206. key := strings.ToLower(table)
  207. rowid, ok := rowIDFromRow(row)
  208. m.cacheMu.Lock()
  209. defer m.cacheMu.Unlock()
  210. if ok {
  211. if byRowID, exists := m.rowIDMap[key]; exists {
  212. delete(byRowID, rowid)
  213. }
  214. }
  215. if cached, exists := m.rowCache[key]; exists && ok {
  216. for i, r := range cached {
  217. if rid, rok := rowIDFromRow(r); rok && rid == rowid {
  218. m.rowCache[key] = append(cached[:i], cached[i+1:]...)
  219. break
  220. }
  221. }
  222. }
  223. }
  224. // cacheUpdate replaces a row in the in-memory row cache if it is already loaded.
  225. func (m *TableManager) cacheUpdate(table string, row Row) {
  226. key := strings.ToLower(table)
  227. rowid, ok := rowIDFromRow(row)
  228. m.cacheMu.Lock()
  229. defer m.cacheMu.Unlock()
  230. if ok {
  231. if byRowID, exists := m.rowIDMap[key]; exists {
  232. byRowID[rowid] = row
  233. }
  234. }
  235. if cached, exists := m.rowCache[key]; exists && ok {
  236. for i, r := range cached {
  237. if rid, rok := rowIDFromRow(r); rok && rid == rowid {
  238. m.rowCache[key][i] = row
  239. break
  240. }
  241. }
  242. }
  243. }
  244. // dataKey returns the key for a row.
  245. func (m *TableManager) dataKey(table, pk string) string {
  246. return fmt.Sprintf("%s:_data:%s:%s", m.database, strings.ToLower(table), pk)
  247. }
  248. // dataPrefix returns the prefix for all rows in a table.
  249. func (m *TableManager) dataPrefix(table string) string {
  250. return fmt.Sprintf("%s:_data:%s:", m.database, strings.ToLower(table))
  251. }
  252. // Insert inserts a new row.
  253. func (m *TableManager) Insert(table string, row Row) error {
  254. schema, err := m.schema.GetSchema(table)
  255. if err != nil {
  256. return err
  257. }
  258. // Get primary key value
  259. pkValue, ok := row[schema.PrimaryKey]
  260. if !ok {
  261. // Try case-insensitive lookup
  262. for k, v := range row {
  263. if strings.EqualFold(k, schema.PrimaryKey) {
  264. pkValue = v
  265. ok = true
  266. break
  267. }
  268. }
  269. }
  270. // Check if PK is INTEGER PRIMARY KEY (implicit ROWID alias)
  271. pkCol, _ := schema.GetColumn(schema.PrimaryKey)
  272. isIntegerPK := pkCol != nil && isIntegerType(pkCol.Type)
  273. // Auto-generate ROWID if no primary key provided or if it's INTEGER PRIMARY KEY
  274. var rowid int64
  275. if !ok || pkValue == nil {
  276. if isIntegerPK || !ok {
  277. // Generate ROWID
  278. rowid, err = m.schema.GetNextRowID(table)
  279. if err != nil {
  280. return err
  281. }
  282. pkValue = rowid
  283. row[schema.PrimaryKey] = rowid
  284. ok = true
  285. } else {
  286. return fmt.Errorf("missing primary key: %s", schema.PrimaryKey)
  287. }
  288. } else if isIntegerPK {
  289. // User provided INTEGER PRIMARY KEY value - track it
  290. switch v := pkValue.(type) {
  291. case int64:
  292. rowid = v
  293. case float64:
  294. rowid = int64(v)
  295. case int:
  296. rowid = int64(v)
  297. default:
  298. rowid = 0
  299. }
  300. if rowid > 0 {
  301. m.schema.UpdateMaxRowID(table, rowid)
  302. }
  303. }
  304. pk := fmt.Sprintf("%v", pkValue)
  305. tl := m.tableLock(strings.ToLower(table))
  306. tl.Lock()
  307. defer tl.Unlock()
  308. // Keep the duplicate check and write in one per-table critical section so
  309. // concurrent inserts of the same primary key cannot both update the cache
  310. // and row count for a single durable row.
  311. key := m.dataKey(table, pk)
  312. err = m.pool.WithClient(func(c *KVClient) error {
  313. _, err := c.Read(key)
  314. return err
  315. })
  316. if err == nil {
  317. return fmt.Errorf("duplicate primary key: %s", pk)
  318. }
  319. // Validate required columns
  320. for _, col := range schema.Columns {
  321. if !col.Nullable && col.Default == nil {
  322. val, hasVal := row[col.Name]
  323. if !hasVal {
  324. // Try case-insensitive lookup
  325. for k, v := range row {
  326. if strings.EqualFold(k, col.Name) {
  327. val = v
  328. hasVal = true
  329. break
  330. }
  331. }
  332. }
  333. if !hasVal || val == nil {
  334. return fmt.Errorf("missing required column: %s", col.Name)
  335. }
  336. }
  337. }
  338. // Normalize column names to match schema
  339. normalizedRow := make(Row)
  340. for _, col := range schema.Columns {
  341. for k, v := range row {
  342. if strings.EqualFold(k, col.Name) {
  343. normalizedRow[col.Name] = v
  344. break
  345. }
  346. }
  347. }
  348. // Apply defaults
  349. for _, col := range schema.Columns {
  350. if _, ok := normalizedRow[col.Name]; !ok && col.Default != nil {
  351. normalizedRow[col.Name] = col.Default
  352. }
  353. }
  354. // Store ROWID (use PK value for INTEGER PRIMARY KEY, otherwise generate)
  355. if rowid > 0 {
  356. normalizedRow["_rowid_"] = rowid
  357. } else {
  358. // Generate ROWID for non-integer primary keys
  359. newRowID, _ := m.schema.GetNextRowID(table)
  360. normalizedRow["_rowid_"] = newRowID
  361. }
  362. // Serialize row
  363. data, err := json.Marshal(normalizedRow)
  364. if err != nil {
  365. return fmt.Errorf("failed to serialize row: %w", err)
  366. }
  367. err = m.pool.WithClient(func(c *KVClient) error {
  368. return c.Write(key, string(data))
  369. })
  370. if err != nil {
  371. return err
  372. }
  373. // Update in-memory indexes only. Durable index entries are derived from rows.
  374. m.updateIndexesForRow(table, normalizedRow, true)
  375. m.cacheInsert(table, normalizedRow)
  376. m.incrCount(table, 1)
  377. return nil
  378. }
  379. // InsertBulk inserts multiple rows efficiently, parallelizing KV writes across
  380. // the connection pool. Skips per-row duplicate checks (caller must ensure
  381. // uniqueness). Used by INSERT ... SELECT.
  382. func (m *TableManager) InsertBulk(table string, rows []Row) (int, error) {
  383. if len(rows) == 0 {
  384. return 0, nil
  385. }
  386. schema, err := m.schema.GetSchema(table)
  387. if err != nil {
  388. return 0, err
  389. }
  390. pkCol, _ := schema.GetColumn(schema.PrimaryKey)
  391. isIntegerPK := pkCol != nil && isIntegerType(pkCol.Type)
  392. // Normalize rows and assign _rowid_.
  393. normalized := make([]Row, 0, len(rows))
  394. var maxRowID int64
  395. for _, row := range rows {
  396. nr := make(Row)
  397. for _, col := range schema.Columns {
  398. for k, v := range row {
  399. if strings.EqualFold(k, col.Name) {
  400. nr[col.Name] = v
  401. break
  402. }
  403. }
  404. }
  405. for _, col := range schema.Columns {
  406. if _, ok := nr[col.Name]; !ok && col.Default != nil {
  407. nr[col.Name] = col.Default
  408. }
  409. }
  410. var rowid int64
  411. var hasRowid bool
  412. if isIntegerPK {
  413. switch v := nr[schema.PrimaryKey].(type) {
  414. case float64:
  415. rowid = int64(v)
  416. hasRowid = true
  417. case int64:
  418. rowid = v
  419. hasRowid = true
  420. case int:
  421. rowid = int64(v)
  422. hasRowid = true
  423. }
  424. }
  425. if !hasRowid {
  426. // Fall back to sequential insert for non-integer-pk rows.
  427. if err := m.Insert(table, row); err != nil {
  428. return len(normalized), err
  429. }
  430. continue
  431. }
  432. nr["_rowid_"] = rowid
  433. if rowid > maxRowID {
  434. maxRowID = rowid
  435. }
  436. normalized = append(normalized, nr)
  437. }
  438. if maxRowID > 0 {
  439. m.schema.UpdateMaxRowID(table, maxRowID)
  440. }
  441. // Serialize all rows.
  442. type kv struct{ key, val string }
  443. rowKVs := make([]kv, 0, len(normalized))
  444. for _, nr := range normalized {
  445. pk := fmt.Sprintf("%v", nr[schema.PrimaryKey])
  446. data, err := json.Marshal(nr)
  447. if err != nil {
  448. return 0, err
  449. }
  450. rowKVs = append(rowKVs, kv{m.dataKey(table, pk), string(data)})
  451. }
  452. // Hold the per-table lock for the whole write+maintain phase so a
  453. // concurrent cache/count load cannot scan a partially-written table.
  454. tl := m.tableLock(strings.ToLower(table))
  455. tl.Lock()
  456. defer tl.Unlock()
  457. // Write rows concurrently.
  458. errs := make([]error, len(rowKVs))
  459. var wg sync.WaitGroup
  460. for i, w := range rowKVs {
  461. wg.Add(1)
  462. i, w := i, w
  463. go func() {
  464. defer wg.Done()
  465. errs[i] = m.pool.WithClient(func(c *KVClient) error {
  466. return c.Write(w.key, w.val)
  467. })
  468. }()
  469. }
  470. wg.Wait()
  471. // Maintain in-memory caches only for rows that actually persisted, so a
  472. // partial failure cannot leave an already-loaded cache/count stale.
  473. var firstErr error
  474. numOK := 0
  475. for i, e := range errs {
  476. if e != nil {
  477. if firstErr == nil {
  478. firstErr = e
  479. }
  480. continue
  481. }
  482. m.updateIndexesForRow(table, normalized[i], true)
  483. m.cacheInsert(table, normalized[i])
  484. numOK++
  485. }
  486. m.incrCount(table, numOK)
  487. return numOK, firstErr
  488. }
  489. // updateIndexesForRow adds or removes entries from already-built in-memory
  490. // indexes. Index entries are rebuildable from durable row data, so this method
  491. // intentionally does not write idx:* keys to KV.
  492. func (m *TableManager) updateIndexesForRow(table string, row Row, add bool) {
  493. indexes, err := m.schema.ListTableIndexes(table)
  494. if err != nil || len(indexes) == 0 {
  495. return
  496. }
  497. rowid, ok := rowIDFromRow(row)
  498. if !ok {
  499. return
  500. }
  501. for _, idx := range indexes {
  502. indexName := strings.ToLower(idx.Name)
  503. m.cacheMu.RLock()
  504. _, initialized := m.indexCache[indexName]
  505. m.cacheMu.RUnlock()
  506. if !initialized {
  507. continue
  508. }
  509. columns := make([]string, len(idx.Columns))
  510. for i, col := range idx.Columns {
  511. columns[i] = col.Name
  512. }
  513. colValue := m.buildIndexValue(row, columns)
  514. if add {
  515. m.AddIndexEntry(idx.Name, colValue, rowid)
  516. } else {
  517. m.RemoveIndexEntry(idx.Name, colValue, rowid)
  518. }
  519. }
  520. }
  521. // Select retrieves rows from a table.
  522. func (m *TableManager) Select(table string, filter func(Row) bool) ([]Row, error) {
  523. if !m.schema.TableExists(table) {
  524. return nil, fmt.Errorf("table not found: %s", table)
  525. }
  526. key := strings.ToLower(table)
  527. if err := m.loadTable(key, table); err != nil {
  528. return nil, err
  529. }
  530. // Snapshot row references under the read lock, then filter and clone only
  531. // matching rows without holding a lock. Published cached rows are immutable:
  532. // writers replace row references rather than mutating their maps in place.
  533. // This keeps selective scans from allocating a map for every examined row.
  534. m.cacheMu.RLock()
  535. cached := m.rowCache[key]
  536. snapshot := append([]Row(nil), cached...)
  537. m.cacheMu.RUnlock()
  538. if filter == nil {
  539. rows := make([]Row, len(snapshot))
  540. for i, row := range snapshot {
  541. rows[i] = cloneRow(row)
  542. }
  543. return rows, nil
  544. }
  545. rows := make([]Row, 0, len(snapshot))
  546. for _, row := range snapshot {
  547. if filter(row) {
  548. rows = append(rows, cloneRow(row))
  549. }
  550. }
  551. return rows, nil
  552. }
  553. func cloneRow(row Row) Row {
  554. if row == nil {
  555. return nil
  556. }
  557. cloned := make(Row, len(row))
  558. for k, v := range row {
  559. cloned[k] = v
  560. }
  561. return cloned
  562. }
  563. // SelectWithLimit retrieves rows with limit and offset.
  564. func (m *TableManager) SelectWithLimit(table string, filter func(Row) bool, limit, offset int) ([]Row, error) {
  565. rows, err := m.Select(table, filter)
  566. if err != nil {
  567. return nil, err
  568. }
  569. // Apply offset
  570. if offset > 0 {
  571. if offset >= len(rows) {
  572. return nil, nil
  573. }
  574. rows = rows[offset:]
  575. }
  576. // Apply limit
  577. if limit > 0 && limit < len(rows) {
  578. rows = rows[:limit]
  579. }
  580. return rows, nil
  581. }
  582. // Update updates rows matching the filter.
  583. func (m *TableManager) Update(table string, updates Row, filter func(Row) bool) (int, error) {
  584. schema, err := m.schema.GetSchema(table)
  585. if err != nil {
  586. return 0, err
  587. }
  588. // Get all rows
  589. rows, err := m.Select(table, filter)
  590. if err != nil {
  591. return 0, err
  592. }
  593. tl := m.tableLock(strings.ToLower(table))
  594. tl.Lock()
  595. defer tl.Unlock()
  596. count := 0
  597. for _, row := range rows {
  598. // Snapshot the pre-update row so removed index entries can be restored
  599. // if persistence fails.
  600. oldRow := cloneRow(row)
  601. m.updateIndexesForRow(table, row, false)
  602. // Apply updates
  603. for k, v := range updates {
  604. // Normalize column name
  605. for _, col := range schema.Columns {
  606. if strings.EqualFold(k, col.Name) {
  607. row[col.Name] = v
  608. break
  609. }
  610. }
  611. }
  612. // Get primary key
  613. pkValue := row[schema.PrimaryKey]
  614. pk := fmt.Sprintf("%v", pkValue)
  615. // Serialize row
  616. data, err := json.Marshal(row)
  617. if err != nil {
  618. m.updateIndexesForRow(table, oldRow, true)
  619. continue
  620. }
  621. // Write back
  622. key := m.dataKey(table, pk)
  623. err = m.pool.WithClient(func(c *KVClient) error {
  624. return c.Write(key, string(data))
  625. })
  626. if err == nil {
  627. // Add new index entries after update
  628. m.updateIndexesForRow(table, row, true)
  629. m.cacheUpdate(table, row)
  630. count++
  631. } else {
  632. m.updateIndexesForRow(table, oldRow, true)
  633. }
  634. }
  635. return count, nil
  636. }
  637. // UpdateFunc updates rows matching the filter using a function to compute new values.
  638. // The updateFn receives the current row and returns the updates to apply.
  639. func (m *TableManager) UpdateFunc(table string, updateFn func(Row) (Row, error), filter func(Row) bool) (int, error) {
  640. schema, err := m.schema.GetSchema(table)
  641. if err != nil {
  642. return 0, err
  643. }
  644. // Get all rows
  645. rows, err := m.Select(table, filter)
  646. if err != nil {
  647. return 0, err
  648. }
  649. tl := m.tableLock(strings.ToLower(table))
  650. tl.Lock()
  651. defer tl.Unlock()
  652. count := 0
  653. for _, row := range rows {
  654. oldRow := cloneRow(row)
  655. m.updateIndexesForRow(table, row, false)
  656. // Compute updates using the provided function
  657. updates, err := updateFn(row)
  658. if err != nil {
  659. m.updateIndexesForRow(table, oldRow, true)
  660. return count, err
  661. }
  662. // Apply updates
  663. for k, v := range updates {
  664. // Normalize column name
  665. for _, col := range schema.Columns {
  666. if strings.EqualFold(k, col.Name) {
  667. row[col.Name] = v
  668. break
  669. }
  670. }
  671. }
  672. // Get primary key
  673. pkValue := row[schema.PrimaryKey]
  674. pk := fmt.Sprintf("%v", pkValue)
  675. // Serialize row
  676. data, err := json.Marshal(row)
  677. if err != nil {
  678. m.updateIndexesForRow(table, oldRow, true)
  679. continue
  680. }
  681. // Write back
  682. key := m.dataKey(table, pk)
  683. err = m.pool.WithClient(func(c *KVClient) error {
  684. return c.Write(key, string(data))
  685. })
  686. if err == nil {
  687. // Add new index entries after update
  688. m.updateIndexesForRow(table, row, true)
  689. m.cacheUpdate(table, row)
  690. count++
  691. } else {
  692. m.updateIndexesForRow(table, oldRow, true)
  693. }
  694. }
  695. return count, nil
  696. }
  697. // Delete deletes rows matching the filter.
  698. func (m *TableManager) Delete(table string, filter func(Row) bool) (int, error) {
  699. schema, err := m.schema.GetSchema(table)
  700. if err != nil {
  701. return 0, err
  702. }
  703. // Get all rows
  704. rows, err := m.Select(table, filter)
  705. if err != nil {
  706. return 0, err
  707. }
  708. tl := m.tableLock(strings.ToLower(table))
  709. tl.Lock()
  710. defer tl.Unlock()
  711. count := 0
  712. for _, row := range rows {
  713. // Remove index entries before deleting row
  714. m.updateIndexesForRow(table, row, false)
  715. pkValue := row[schema.PrimaryKey]
  716. pk := fmt.Sprintf("%v", pkValue)
  717. key := m.dataKey(table, pk)
  718. err = m.pool.WithClient(func(c *KVClient) error {
  719. return c.Delete(key)
  720. })
  721. if err == nil {
  722. m.cacheDelete(table, row)
  723. count++
  724. } else {
  725. // Restore the index entries removed above.
  726. m.updateIndexesForRow(table, row, true)
  727. }
  728. }
  729. m.incrCount(table, -count)
  730. return count, nil
  731. }
  732. // GetByPK retrieves a row by primary key.
  733. func (m *TableManager) GetByPK(table string, pk string) (Row, error) {
  734. if !m.schema.TableExists(table) {
  735. return nil, fmt.Errorf("table not found: %s", table)
  736. }
  737. key := m.dataKey(table, pk)
  738. var data string
  739. err := m.pool.WithClient(func(c *KVClient) error {
  740. var err error
  741. data, err = c.Read(key)
  742. return err
  743. })
  744. if err != nil {
  745. if err == ErrKeyNotFound {
  746. return nil, fmt.Errorf("row not found: %s", pk)
  747. }
  748. return nil, err
  749. }
  750. var row Row
  751. if err := json.Unmarshal([]byte(data), &row); err != nil {
  752. return nil, fmt.Errorf("failed to parse row: %w", err)
  753. }
  754. return row, nil
  755. }
  756. // Count returns the number of rows in a table.
  757. func (m *TableManager) Count(table string, filter func(Row) bool) (int, error) {
  758. rows, err := m.Select(table, filter)
  759. if err != nil {
  760. return 0, err
  761. }
  762. return len(rows), nil
  763. }
  764. // Truncate removes all rows from a table.
  765. func (m *TableManager) Truncate(table string) (int, error) {
  766. return m.Delete(table, nil)
  767. }
  768. // isIntegerType checks if a type name is an integer type.
  769. func isIntegerType(typeName string) bool {
  770. t := strings.ToUpper(typeName)
  771. switch t {
  772. case "INTEGER", "INT", "SMALLINT", "BIGINT", "TINYINT", "MEDIUMINT":
  773. return true
  774. }
  775. return false
  776. }
  777. // IsRowIDColumn checks if a column name is a ROWID alias.
  778. func IsRowIDColumn(name string) bool {
  779. n := strings.ToLower(name)
  780. return n == "rowid" || n == "oid" || n == "_rowid_"
  781. }
  782. // Index entry methods - leveraging radix trie for prefix-based lookups
  783. // Format: {database}:idx:{index_name}:{column_value} → JSON array of rowids
  784. // indexEntryKey returns the key for an index entry.
  785. func (m *TableManager) indexEntryKey(indexName string, colValue interface{}) string {
  786. return fmt.Sprintf("%s:idx:%s:%s", m.database, strings.ToLower(indexName), formatIndexValue(colValue))
  787. }
  788. // indexPrefix returns the prefix for all entries of an index.
  789. func (m *TableManager) indexPrefix(indexName string) string {
  790. return fmt.Sprintf("%s:idx:%s:", m.database, strings.ToLower(indexName))
  791. }
  792. func formatIndexValue(value interface{}) string {
  793. switch v := value.(type) {
  794. case float64:
  795. if v == float64(int64(v)) {
  796. return fmt.Sprintf("%d", int64(v))
  797. }
  798. return fmt.Sprintf("%f", v)
  799. case int64:
  800. return fmt.Sprintf("%d", v)
  801. case int:
  802. return fmt.Sprintf("%d", v)
  803. default:
  804. return fmt.Sprintf("%v", v)
  805. }
  806. }
  807. func rowIDFromRow(row Row) (int64, bool) {
  808. switch v := row["_rowid_"].(type) {
  809. case int64:
  810. return v, true
  811. case int:
  812. return int64(v), true
  813. case float64:
  814. return int64(v), true
  815. default:
  816. return 0, false
  817. }
  818. }
  819. func (m *TableManager) ensureIndex(index *Index) error {
  820. indexKey := strings.ToLower(index.Name)
  821. m.cacheMu.RLock()
  822. disabled := m.disabledIndexes[indexKey]
  823. _, initialized := m.indexCache[indexKey]
  824. m.cacheMu.RUnlock()
  825. if disabled {
  826. return nil
  827. }
  828. if initialized {
  829. return nil
  830. }
  831. // Serialize index build against writes to the same table so the derived
  832. // entries cannot miss a concurrently-inserted row.
  833. table := index.Table
  834. key := strings.ToLower(table)
  835. tl := m.tableLock(key)
  836. tl.Lock()
  837. defer tl.Unlock()
  838. m.cacheMu.RLock()
  839. disabled = m.disabledIndexes[indexKey]
  840. _, initialized = m.indexCache[indexKey]
  841. m.cacheMu.RUnlock()
  842. if disabled {
  843. return nil
  844. }
  845. if initialized {
  846. return nil
  847. }
  848. if err := m.loadTableLocked(key, table); err != nil {
  849. return err
  850. }
  851. columns := make([]string, len(index.Columns))
  852. for i, col := range index.Columns {
  853. columns[i] = col.Name
  854. }
  855. m.cacheMu.RLock()
  856. rows := m.rowCache[key]
  857. values := make(map[string][]int64)
  858. for _, row := range rows {
  859. rowid, ok := rowIDFromRow(row)
  860. if !ok {
  861. continue
  862. }
  863. colValue := m.buildIndexValue(row, columns)
  864. valueKey := formatIndexValue(colValue)
  865. values[valueKey] = append(values[valueKey], rowid)
  866. }
  867. m.cacheMu.RUnlock()
  868. m.cacheMu.Lock()
  869. if _, initialized := m.indexCache[indexKey]; !initialized {
  870. m.indexCache[indexKey] = values
  871. m.indexTable[indexKey] = key
  872. }
  873. m.cacheMu.Unlock()
  874. return nil
  875. }
  876. // AddIndexEntry adds a rowid to an in-memory index entry.
  877. func (m *TableManager) AddIndexEntry(indexName string, colValue interface{}, rowid int64) error {
  878. indexKey := strings.ToLower(indexName)
  879. valueKey := formatIndexValue(colValue)
  880. m.cacheMu.Lock()
  881. defer m.cacheMu.Unlock()
  882. values, ok := m.indexCache[indexKey]
  883. if !ok {
  884. return nil
  885. }
  886. rowids := values[valueKey]
  887. for _, r := range rowids {
  888. if r == rowid {
  889. return nil
  890. }
  891. }
  892. values[valueKey] = append(rowids, rowid)
  893. return nil
  894. }
  895. // RemoveIndexEntry removes a rowid from an in-memory index entry.
  896. func (m *TableManager) RemoveIndexEntry(indexName string, colValue interface{}, rowid int64) error {
  897. indexKey := strings.ToLower(indexName)
  898. valueKey := formatIndexValue(colValue)
  899. m.cacheMu.Lock()
  900. defer m.cacheMu.Unlock()
  901. values, ok := m.indexCache[indexKey]
  902. if !ok {
  903. return nil
  904. }
  905. rowids := values[valueKey]
  906. newRowids := make([]int64, 0, len(rowids))
  907. for _, r := range rowids {
  908. if r != rowid {
  909. newRowids = append(newRowids, r)
  910. }
  911. }
  912. if len(newRowids) == 0 {
  913. delete(values, valueKey)
  914. return nil
  915. }
  916. values[valueKey] = newRowids
  917. return nil
  918. }
  919. // LookupIndex returns rowids matching a column value using the index.
  920. func (m *TableManager) LookupIndex(indexName string, colValue interface{}) ([]int64, error) {
  921. index, err := m.schema.GetIndex(indexName)
  922. if err != nil {
  923. return nil, err
  924. }
  925. if err := m.ensureIndex(index); err != nil {
  926. return nil, err
  927. }
  928. indexKey := strings.ToLower(indexName)
  929. valueKey := formatIndexValue(colValue)
  930. m.cacheMu.RLock()
  931. rowids := append([]int64(nil), m.indexCache[indexKey][valueKey]...)
  932. m.cacheMu.RUnlock()
  933. return rowids, nil
  934. }
  935. // ClearIndex removes all entries for an index by scanning table and removing entries.
  936. func (m *TableManager) ClearIndex(indexName, tableName string, columns []string) error {
  937. indexKey := strings.ToLower(indexName)
  938. m.cacheMu.Lock()
  939. delete(m.indexCache, indexKey)
  940. delete(m.indexTable, indexKey)
  941. m.disabledIndexes[indexKey] = true
  942. m.cacheMu.Unlock()
  943. rows, err := m.Select(tableName, nil)
  944. if err != nil {
  945. return err
  946. }
  947. for _, row := range rows {
  948. colValue := m.buildIndexValue(row, columns)
  949. key := m.indexEntryKey(indexName, colValue)
  950. m.pool.WithClient(func(c *KVClient) error {
  951. return c.Delete(key)
  952. })
  953. }
  954. return nil
  955. }
  956. // BuildIndex builds index entries for all existing rows in a table.
  957. func (m *TableManager) BuildIndex(indexName, tableName string, columns []string) error {
  958. indexKey := strings.ToLower(indexName)
  959. m.cacheMu.Lock()
  960. delete(m.disabledIndexes, indexKey)
  961. delete(m.indexCache, indexKey)
  962. delete(m.indexTable, indexKey)
  963. m.cacheMu.Unlock()
  964. index, err := m.schema.GetIndex(indexName)
  965. if err == nil {
  966. return m.ensureIndex(index)
  967. }
  968. rows, err := m.Select(tableName, nil)
  969. if err != nil {
  970. return err
  971. }
  972. values := make(map[string][]int64)
  973. for _, row := range rows {
  974. rowid, ok := rowIDFromRow(row)
  975. if !ok {
  976. continue
  977. }
  978. colValue := m.buildIndexValue(row, columns)
  979. values[formatIndexValue(colValue)] = append(values[formatIndexValue(colValue)], rowid)
  980. }
  981. m.cacheMu.Lock()
  982. m.indexCache[indexKey] = values
  983. m.indexTable[indexKey] = strings.ToLower(tableName)
  984. m.cacheMu.Unlock()
  985. return nil
  986. }
  987. // buildIndexValue creates the index key value from row columns.
  988. func (m *TableManager) buildIndexValue(row Row, columns []string) string {
  989. formatValue := func(v interface{}) string {
  990. switch val := v.(type) {
  991. case float64:
  992. // Check if it's actually an integer value
  993. if val == float64(int64(val)) {
  994. return fmt.Sprintf("%d", int64(val))
  995. }
  996. return fmt.Sprintf("%f", val)
  997. case int64:
  998. return fmt.Sprintf("%d", val)
  999. case int:
  1000. return fmt.Sprintf("%d", val)
  1001. default:
  1002. return fmt.Sprintf("%v", val)
  1003. }
  1004. }
  1005. if len(columns) == 1 {
  1006. return formatValue(row[columns[0]])
  1007. }
  1008. // Multi-column index: concatenate values with separator
  1009. var parts []string
  1010. for _, col := range columns {
  1011. parts = append(parts, formatValue(row[col]))
  1012. }
  1013. return strings.Join(parts, "\x00")
  1014. }
  1015. // SelectByIndex retrieves rows using an index lookup.
  1016. func (m *TableManager) SelectByIndex(table, indexName string, colValue interface{}) ([]Row, error) {
  1017. rowids, err := m.LookupIndex(indexName, colValue)
  1018. if err != nil {
  1019. return nil, err
  1020. }
  1021. // If no rowids found, return empty result
  1022. if len(rowids) == 0 {
  1023. return []Row{}, nil
  1024. }
  1025. // Ensure the rowID map is loaded, then look up and clone rows under the
  1026. // read lock so writers cannot mutate the map concurrently.
  1027. key := strings.ToLower(table)
  1028. if err := m.loadTable(key, table); err != nil {
  1029. return nil, err
  1030. }
  1031. m.cacheMu.RLock()
  1032. byRowID := m.rowIDMap[key]
  1033. rows := make([]Row, 0, len(rowids))
  1034. seen := make(map[int64]struct{}, len(rowids))
  1035. for _, rid := range rowids {
  1036. if _, duplicate := seen[rid]; duplicate {
  1037. continue
  1038. }
  1039. seen[rid] = struct{}{}
  1040. if row, ok := byRowID[rid]; ok {
  1041. rows = append(rows, cloneRow(row))
  1042. }
  1043. }
  1044. m.cacheMu.RUnlock()
  1045. return rows, nil
  1046. }