schema.go 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  1. package storage
  2. import (
  3. "errors"
  4. "fmt"
  5. "strings"
  6. "sync"
  7. "time"
  8. "github.com/goccy/go-json"
  9. "github.com/danfragoso/pizzasql-next/pkg/analyzer"
  10. )
  11. // ErrIndexNotFound is returned by GetIndex when an index is absent. It is
  12. // distinct from a storage/IO error so callers like ListTableIndexes can skip a
  13. // concurrently-dropped index without swallowing real read failures.
  14. var ErrIndexNotFound = errors.New("index not found")
  15. // Schema represents a table schema.
  16. type Schema struct {
  17. Name string `json:"name"`
  18. Columns []Column `json:"columns"`
  19. PrimaryKey string `json:"primary_key"`
  20. CreatedAt time.Time `json:"created_at"`
  21. NextRowID int64 `json:"next_rowid"`
  22. AutoIncrement bool `json:"autoincrement"`
  23. }
  24. // Column represents a column definition.
  25. type Column struct {
  26. Name string `json:"name"`
  27. Type string `json:"type"`
  28. Nullable bool `json:"nullable"`
  29. Default interface{} `json:"default,omitempty"`
  30. PrimaryKey bool `json:"primary_key"`
  31. }
  32. // Index represents an index definition.
  33. type Index struct {
  34. Name string `json:"name"`
  35. Table string `json:"table"`
  36. Columns []IndexColumn `json:"columns"`
  37. Unique bool `json:"unique"`
  38. CreatedAt time.Time `json:"created_at"`
  39. }
  40. // IndexColumn represents a column in an index.
  41. type IndexColumn struct {
  42. Name string `json:"name"`
  43. Desc bool `json:"desc"`
  44. }
  45. // rowIDAllocator owns the next-ROWID state for a single table. It is a separate
  46. // mutex per table so allocating a ROWID on one table never serializes against
  47. // another table, and never contends with the SchemaManager catalog lock.
  48. type rowIDAllocator struct {
  49. mu sync.Mutex
  50. next int64
  51. init bool
  52. }
  53. // SchemaManager manages table schemas.
  54. type SchemaManager struct {
  55. pool *KVPool
  56. database string
  57. cache map[string]*Schema
  58. indexCache map[string]*Index
  59. indexListCache []string
  60. indexListCached bool
  61. version uint64
  62. mu sync.RWMutex
  63. tableLocksMu sync.Mutex
  64. tableLocks map[string]*sync.RWMutex
  65. rowIDMu sync.Mutex
  66. rowIDAlloc map[string]*rowIDAllocator
  67. }
  68. // BeginTransaction is retained for API compatibility. Buffered per-session
  69. // transactions no longer take a database-wide transaction lock; staged writes
  70. // are validated and committed atomically with CompareBatchWrite instead.
  71. func (m *SchemaManager) BeginTransaction() {}
  72. // EndTransaction is retained for API compatibility.
  73. func (m *SchemaManager) EndTransaction() {}
  74. // LockStatement is retained for API compatibility. Statement execution is now
  75. // serialized through per-table locks and optimistic validation, so no global
  76. // statement lock is required.
  77. func (m *SchemaManager) LockStatement() {}
  78. // UnlockStatement is retained for API compatibility.
  79. func (m *SchemaManager) UnlockStatement() {}
  80. // NewSchemaManager creates a new schema manager.
  81. func NewSchemaManager(pool *KVPool, database string) *SchemaManager {
  82. return &SchemaManager{
  83. pool: pool,
  84. database: database,
  85. cache: make(map[string]*Schema),
  86. indexCache: make(map[string]*Index),
  87. tableLocks: make(map[string]*sync.RWMutex),
  88. rowIDAlloc: make(map[string]*rowIDAllocator),
  89. }
  90. }
  91. // rowIDAllocatorFor returns (creating if needed) the per-table ROWID allocator.
  92. func (m *SchemaManager) rowIDAllocatorFor(table string) *rowIDAllocator {
  93. key := strings.ToLower(table)
  94. m.rowIDMu.Lock()
  95. a, ok := m.rowIDAlloc[key]
  96. if !ok {
  97. a = &rowIDAllocator{}
  98. m.rowIDAlloc[key] = a
  99. }
  100. m.rowIDMu.Unlock()
  101. return a
  102. }
  103. func (m *SchemaManager) tableLock(table string) *sync.RWMutex {
  104. key := strings.ToLower(table)
  105. m.tableLocksMu.Lock()
  106. lock, ok := m.tableLocks[key]
  107. if !ok {
  108. lock = &sync.RWMutex{}
  109. m.tableLocks[key] = lock
  110. }
  111. m.tableLocksMu.Unlock()
  112. return lock
  113. }
  114. // GetDatabaseName returns the database name.
  115. func (m *SchemaManager) GetDatabaseName() string {
  116. return m.database
  117. }
  118. // GetPool returns the KV pool.
  119. func (m *SchemaManager) GetPool() *KVPool {
  120. return m.pool
  121. }
  122. // Version returns the in-process schema catalog version. It is incremented for
  123. // schema/index definition changes so cached executors can resync their analyzer
  124. // catalogs without scanning storage on every query.
  125. func (m *SchemaManager) Version() uint64 {
  126. m.mu.RLock()
  127. defer m.mu.RUnlock()
  128. return m.version
  129. }
  130. func (m *SchemaManager) bumpVersionLocked() {
  131. m.version++
  132. }
  133. // schemaKey returns the key for a table schema.
  134. func (m *SchemaManager) schemaKey(table string) string {
  135. return fmt.Sprintf("%s:_schema:%s", m.database, strings.ToLower(table))
  136. }
  137. // catalogKey returns the key for the table catalog.
  138. func (m *SchemaManager) catalogKey() string {
  139. return fmt.Sprintf("%s:_sys:tables", m.database)
  140. }
  141. // rowIDKey returns the key for a table's next ROWID counter.
  142. func (m *SchemaManager) rowIDKey(table string) string {
  143. return fmt.Sprintf("%s:_sys:rowid:%s", m.database, strings.ToLower(table))
  144. }
  145. // CreateTable creates a new table.
  146. func (m *SchemaManager) CreateTable(schema *Schema) error {
  147. m.mu.Lock()
  148. defer m.mu.Unlock()
  149. // Check if table already exists
  150. key := m.schemaKey(schema.Name)
  151. err := m.pool.WithClient(func(c *KVClient) error {
  152. _, err := c.Read(key)
  153. return err
  154. })
  155. if err == nil {
  156. return fmt.Errorf("table already exists: %s", schema.Name)
  157. }
  158. // Keep the cached schema private so callers cannot mutate a published
  159. // catalog snapshot after this operation returns.
  160. schema = cloneSchema(schema)
  161. schema.CreatedAt = time.Now()
  162. // Determine primary key if not set
  163. if schema.PrimaryKey == "" {
  164. for _, col := range schema.Columns {
  165. if col.PrimaryKey {
  166. schema.PrimaryKey = col.Name
  167. break
  168. }
  169. }
  170. // No explicit primary key declared — use synthetic _rowid_ so user
  171. // columns remain unconstrained and can hold duplicate or NULL values.
  172. if schema.PrimaryKey == "" {
  173. schema.PrimaryKey = "_rowid_"
  174. }
  175. }
  176. // Serialize schema
  177. data, err := json.Marshal(schema)
  178. if err != nil {
  179. return fmt.Errorf("failed to serialize schema: %w", err)
  180. }
  181. // Write schema
  182. err = m.pool.WithClient(func(c *KVClient) error {
  183. return c.Write(key, string(data))
  184. })
  185. if err != nil {
  186. return fmt.Errorf("failed to write schema: %w", err)
  187. }
  188. // Update catalog
  189. if err := m.addToCatalog(schema.Name); err != nil {
  190. // Rollback schema write
  191. m.pool.WithClient(func(c *KVClient) error {
  192. return c.Delete(key)
  193. })
  194. return err
  195. }
  196. // Update cache
  197. m.cache[strings.ToLower(schema.Name)] = schema
  198. m.bumpVersionLocked()
  199. return nil
  200. }
  201. // DropTable drops a table.
  202. func (m *SchemaManager) DropTable(name string) error {
  203. tableLock := m.tableLock(name)
  204. tableLock.Lock()
  205. defer tableLock.Unlock()
  206. m.mu.Lock()
  207. defer m.mu.Unlock()
  208. key := m.schemaKey(name)
  209. // Check if table exists
  210. err := m.pool.WithClient(func(c *KVClient) error {
  211. _, err := c.Read(key)
  212. return err
  213. })
  214. if err != nil {
  215. return fmt.Errorf("table not found: %s", name)
  216. }
  217. // Delete all rows by scanning their actual keys and batch-deleting them, so
  218. // a table drop no longer leaks durable rows.
  219. if err := m.deleteKeysWithPrefix([]byte(fmt.Sprintf("%s:_data:%s:", m.database, strings.ToLower(name)))); err != nil {
  220. return err
  221. }
  222. // Delete schema
  223. err = m.pool.WithClient(func(c *KVClient) error {
  224. return c.Delete(key)
  225. })
  226. if err != nil {
  227. return fmt.Errorf("failed to delete schema: %w", err)
  228. }
  229. // Delete ROWID state.
  230. m.pool.WithClient(func(c *KVClient) error {
  231. return c.Delete(m.rowIDKey(name))
  232. })
  233. // Update catalog
  234. if err := m.removeFromCatalog(name); err != nil {
  235. return err
  236. }
  237. // Update cache
  238. tableLower := strings.ToLower(name)
  239. delete(m.cache, tableLower)
  240. m.rowIDMu.Lock()
  241. delete(m.rowIDAlloc, tableLower)
  242. m.rowIDMu.Unlock()
  243. m.bumpVersionLocked()
  244. return nil
  245. }
  246. // GetSchema retrieves a table schema.
  247. func (m *SchemaManager) GetSchema(name string) (*Schema, error) {
  248. m.mu.RLock()
  249. if schema, ok := m.cache[strings.ToLower(name)]; ok {
  250. // Clone while still holding the read lock: the cached schema's
  251. // NextRowID field is mutated under the write lock, so cloning outside
  252. // the lock races with that mutation.
  253. cloned := cloneSchema(schema)
  254. m.mu.RUnlock()
  255. return cloned, nil
  256. }
  257. m.mu.RUnlock()
  258. m.mu.Lock()
  259. defer m.mu.Unlock()
  260. // Double-check after acquiring write lock
  261. if schema, ok := m.cache[strings.ToLower(name)]; ok {
  262. return cloneSchema(schema), nil
  263. }
  264. key := m.schemaKey(name)
  265. var data string
  266. err := m.pool.WithClient(func(c *KVClient) error {
  267. var err error
  268. data, err = c.Read(key)
  269. return err
  270. })
  271. if err != nil {
  272. if err == ErrKeyNotFound {
  273. return nil, fmt.Errorf("table not found: %s", name)
  274. }
  275. return nil, err
  276. }
  277. var schema Schema
  278. if err := json.Unmarshal([]byte(data), &schema); err != nil {
  279. return nil, fmt.Errorf("failed to parse schema: %w", err)
  280. }
  281. m.cache[strings.ToLower(name)] = &schema
  282. return cloneSchema(&schema), nil
  283. }
  284. func cloneSchema(schema *Schema) *Schema {
  285. if schema == nil {
  286. return nil
  287. }
  288. cloned := *schema
  289. cloned.Columns = append([]Column(nil), schema.Columns...)
  290. return &cloned
  291. }
  292. func cloneIndex(index *Index) *Index {
  293. if index == nil {
  294. return nil
  295. }
  296. cloned := *index
  297. cloned.Columns = append([]IndexColumn(nil), index.Columns...)
  298. return &cloned
  299. }
  300. // TableExists checks if a table exists.
  301. func (m *SchemaManager) TableExists(name string) bool {
  302. _, err := m.GetSchema(name)
  303. return err == nil
  304. }
  305. // ListTables returns all table names.
  306. func (m *SchemaManager) ListTables() ([]string, error) {
  307. var data string
  308. err := m.pool.WithClient(func(c *KVClient) error {
  309. var err error
  310. data, err = c.Read(m.catalogKey())
  311. return err
  312. })
  313. if err != nil {
  314. if err == ErrKeyNotFound {
  315. return nil, nil
  316. }
  317. return nil, err
  318. }
  319. var tables []string
  320. if err := json.Unmarshal([]byte(data), &tables); err != nil {
  321. return nil, fmt.Errorf("failed to parse catalog: %w", err)
  322. }
  323. return tables, nil
  324. }
  325. // addToCatalog adds a table to the catalog.
  326. func (m *SchemaManager) addToCatalog(name string) error {
  327. tables, err := m.ListTables()
  328. if err != nil && err != ErrKeyNotFound {
  329. return err
  330. }
  331. // Check if already exists
  332. lowerName := strings.ToLower(name)
  333. for _, t := range tables {
  334. if strings.ToLower(t) == lowerName {
  335. return nil
  336. }
  337. }
  338. tables = append(tables, name)
  339. data, err := json.Marshal(tables)
  340. if err != nil {
  341. return err
  342. }
  343. return m.pool.WithClient(func(c *KVClient) error {
  344. return c.Write(m.catalogKey(), string(data))
  345. })
  346. }
  347. // removeFromCatalog removes a table from the catalog.
  348. func (m *SchemaManager) removeFromCatalog(name string) error {
  349. tables, err := m.ListTables()
  350. if err != nil {
  351. return err
  352. }
  353. lowerName := strings.ToLower(name)
  354. newTables := make([]string, 0, len(tables))
  355. for _, t := range tables {
  356. if strings.ToLower(t) != lowerName {
  357. newTables = append(newTables, t)
  358. }
  359. }
  360. data, err := json.Marshal(newTables)
  361. if err != nil {
  362. return err
  363. }
  364. return m.pool.WithClient(func(c *KVClient) error {
  365. return c.Write(m.catalogKey(), string(data))
  366. })
  367. }
  368. // InvalidateCache clears the cache for a table.
  369. func (m *SchemaManager) InvalidateCache(name string) {
  370. m.mu.Lock()
  371. defer m.mu.Unlock()
  372. tableLower := strings.ToLower(name)
  373. delete(m.cache, tableLower)
  374. m.rowIDMu.Lock()
  375. delete(m.rowIDAlloc, tableLower)
  376. m.rowIDMu.Unlock()
  377. }
  378. // ToAnalyzerTableInfo converts a Schema to analyzer.TableInfo.
  379. func (s *Schema) ToAnalyzerTableInfo() *analyzer.TableInfo {
  380. info := &analyzer.TableInfo{
  381. Name: s.Name,
  382. }
  383. for _, col := range s.Columns {
  384. info.Columns = append(info.Columns, analyzer.ColumnInfo{
  385. Name: col.Name,
  386. Type: analyzer.TypeFromName(col.Type),
  387. Nullable: col.Nullable,
  388. PrimaryKey: col.PrimaryKey,
  389. TableName: s.Name,
  390. })
  391. }
  392. return info
  393. }
  394. // GetColumn returns a column by name.
  395. func (s *Schema) GetColumn(name string) (*Column, bool) {
  396. lowerName := strings.ToLower(name)
  397. for i := range s.Columns {
  398. if strings.ToLower(s.Columns[i].Name) == lowerName {
  399. return &s.Columns[i], true
  400. }
  401. }
  402. return nil, false
  403. }
  404. // GetNextRowID gets and increments the next ROWID for a table. Allocation is
  405. // serialized per table via the table's own allocator so inserts on different
  406. // tables never contend, and no global SchemaManager lock is held across the
  407. // durable derivation scan.
  408. func (m *SchemaManager) GetNextRowID(table string) (int64, error) {
  409. alloc := m.rowIDAllocatorFor(table)
  410. alloc.mu.Lock()
  411. defer alloc.mu.Unlock()
  412. next, err := m.nextRowIDLocked(alloc, table)
  413. if err != nil {
  414. return 0, err
  415. }
  416. alloc.next = next + 1
  417. return next, nil
  418. }
  419. // UpdateMaxRowID updates the next ROWID if the provided value is higher.
  420. func (m *SchemaManager) UpdateMaxRowID(table string, rowid int64) error {
  421. alloc := m.rowIDAllocatorFor(table)
  422. alloc.mu.Lock()
  423. defer alloc.mu.Unlock()
  424. next, err := m.nextRowIDLocked(alloc, table)
  425. if err != nil {
  426. return err
  427. }
  428. if rowid >= next {
  429. alloc.next = rowid + 1
  430. }
  431. return nil
  432. }
  433. // nextRowIDLocked returns the current next ROWID, deriving it from durable rows
  434. // on first use (must hold the per-table allocator lock).
  435. func (m *SchemaManager) nextRowIDLocked(alloc *rowIDAllocator, table string) (int64, error) {
  436. if alloc.init {
  437. return alloc.next, nil
  438. }
  439. next, err := m.deriveNextRowID(table)
  440. if err != nil {
  441. return 0, err
  442. }
  443. if next < 1 {
  444. next = 1
  445. }
  446. alloc.next = next
  447. alloc.init = true
  448. return alloc.next, nil
  449. }
  450. // deriveNextRowID scans durable row keys to recover max(rowid)+1, streaming
  451. // each page through decodeRow instead of materializing every value.
  452. func (m *SchemaManager) deriveNextRowID(table string) (int64, error) {
  453. prefix := []byte(fmt.Sprintf("%s:_data:%s:", m.database, strings.ToLower(table)))
  454. var maxRowID int64
  455. err := m.pool.WithClient(func(client *KVClient) (retErr error) {
  456. cursor, err := client.Scan(prefix)
  457. if err != nil {
  458. return err
  459. }
  460. defer func() {
  461. if err := cursor.Close(); retErr == nil {
  462. retErr = err
  463. }
  464. }()
  465. for {
  466. entries, done, err := cursor.Next()
  467. if err != nil {
  468. return err
  469. }
  470. for _, e := range entries {
  471. row, err := decodeRow(e.Value)
  472. if err != nil {
  473. return fmt.Errorf("failed to parse row while deriving ROWID: %w", err)
  474. }
  475. if rowid, ok := valueAsInt64(row["_rowid_"]); ok && rowid > maxRowID {
  476. maxRowID = rowid
  477. }
  478. }
  479. if done {
  480. return nil
  481. }
  482. }
  483. })
  484. if err != nil {
  485. return 0, err
  486. }
  487. return maxRowID + 1, nil
  488. }
  489. // deleteKeysWithPrefix streams the keys with the given prefix one page at a
  490. // time and atomically batch-deletes them, so a bulk operation never leaves
  491. // durable rows behind.
  492. func (m *SchemaManager) deleteKeysWithPrefix(prefix []byte) error {
  493. return m.pool.WithClient(func(client *KVClient) (retErr error) {
  494. cursor, err := client.ScanKeys(prefix)
  495. if err != nil {
  496. return err
  497. }
  498. defer func() {
  499. if err := cursor.Close(); retErr == nil {
  500. retErr = err
  501. }
  502. }()
  503. ops := make([]BatchOp, 0, scanPageSize)
  504. batchBytes := 8
  505. flush := func() error {
  506. if len(ops) == 0 {
  507. return nil
  508. }
  509. if _, err := client.BatchWrite(ops, nil); err != nil {
  510. return err
  511. }
  512. ops = ops[:0]
  513. batchBytes = 8
  514. return nil
  515. }
  516. for {
  517. entries, done, err := cursor.Next()
  518. if err != nil {
  519. return err
  520. }
  521. for _, e := range entries {
  522. opBytes := 12 + len(e.Key)
  523. if len(ops) == maxOperations || batchBytes+opBytes > bulkBatchByteBudget {
  524. if err := flush(); err != nil {
  525. return err
  526. }
  527. }
  528. ops = append(ops, BatchOp{Op: batchDelete, Key: append([]byte(nil), e.Key...)})
  529. batchBytes += opBytes
  530. }
  531. if done {
  532. return flush()
  533. }
  534. }
  535. })
  536. }
  537. func valueAsInt64(value interface{}) (int64, bool) {
  538. switch v := value.(type) {
  539. case int64:
  540. return v, true
  541. case int:
  542. return int64(v), true
  543. case float64:
  544. return int64(v), true
  545. default:
  546. return 0, false
  547. }
  548. }
  549. // getSchemaLocked retrieves schema (must hold lock).
  550. func (m *SchemaManager) getSchemaLocked(name string) (*Schema, error) {
  551. if schema, ok := m.cache[strings.ToLower(name)]; ok {
  552. return schema, nil
  553. }
  554. key := m.schemaKey(name)
  555. var data string
  556. err := m.pool.WithClient(func(c *KVClient) error {
  557. var err error
  558. data, err = c.Read(key)
  559. return err
  560. })
  561. if err != nil {
  562. if err == ErrKeyNotFound {
  563. return nil, fmt.Errorf("table not found: %s", name)
  564. }
  565. return nil, err
  566. }
  567. var schema Schema
  568. if err := json.Unmarshal([]byte(data), &schema); err != nil {
  569. return nil, fmt.Errorf("failed to parse schema: %w", err)
  570. }
  571. m.cache[strings.ToLower(name)] = &schema
  572. return &schema, nil
  573. }
  574. // saveSchemaLocked saves schema (must hold lock).
  575. func (m *SchemaManager) saveSchemaLocked(schema *Schema) error {
  576. data, err := json.Marshal(schema)
  577. if err != nil {
  578. return fmt.Errorf("failed to serialize schema: %w", err)
  579. }
  580. key := m.schemaKey(schema.Name)
  581. err = m.pool.WithClient(func(c *KVClient) error {
  582. return c.Write(key, string(data))
  583. })
  584. if err != nil {
  585. return fmt.Errorf("failed to write schema: %w", err)
  586. }
  587. m.cache[strings.ToLower(schema.Name)] = schema
  588. return nil
  589. }
  590. // Index management methods
  591. // indexKey returns the key for an index.
  592. func (m *SchemaManager) indexKey(name string) string {
  593. return fmt.Sprintf("%s:index:%s", m.database, strings.ToLower(name))
  594. }
  595. // indexListKey returns the key for the index list.
  596. func (m *SchemaManager) indexListKey() string {
  597. return fmt.Sprintf("%s:indexes", m.database)
  598. }
  599. // CreateIndex creates a new index.
  600. func (m *SchemaManager) CreateIndex(index *Index) error {
  601. m.mu.Lock()
  602. defer m.mu.Unlock()
  603. // Check if index already exists
  604. key := m.indexKey(index.Name)
  605. err := m.pool.WithClient(func(c *KVClient) error {
  606. _, err := c.Read(key)
  607. return err
  608. })
  609. if err == nil {
  610. return fmt.Errorf("index already exists: %s", index.Name)
  611. }
  612. // Verify table exists
  613. if _, err := m.getSchemaLocked(index.Table); err != nil {
  614. return fmt.Errorf("table not found: %s", index.Table)
  615. }
  616. // Save index
  617. index.CreatedAt = time.Now()
  618. data, err := json.Marshal(index)
  619. if err != nil {
  620. return fmt.Errorf("failed to serialize index: %w", err)
  621. }
  622. err = m.pool.WithClient(func(c *KVClient) error {
  623. return c.Write(key, string(data))
  624. })
  625. if err != nil {
  626. return fmt.Errorf("failed to write index: %w", err)
  627. }
  628. // Add to index list
  629. if err := m.addToIndexList(index.Name); err != nil {
  630. return err
  631. }
  632. m.indexCache[strings.ToLower(index.Name)] = cloneIndex(index)
  633. m.bumpVersionLocked()
  634. return nil
  635. }
  636. // DropIndex drops an index.
  637. func (m *SchemaManager) DropIndex(name string) error {
  638. m.mu.Lock()
  639. defer m.mu.Unlock()
  640. key := m.indexKey(name)
  641. err := m.pool.WithClient(func(c *KVClient) error {
  642. return c.Delete(key)
  643. })
  644. if err != nil {
  645. return fmt.Errorf("failed to delete index: %w", err)
  646. }
  647. if err := m.removeFromIndexList(name); err != nil {
  648. return err
  649. }
  650. delete(m.indexCache, strings.ToLower(name))
  651. m.bumpVersionLocked()
  652. return nil
  653. }
  654. // IndexExists checks if an index exists.
  655. func (m *SchemaManager) IndexExists(name string) bool {
  656. m.mu.RLock()
  657. defer m.mu.RUnlock()
  658. if _, ok := m.indexCache[strings.ToLower(name)]; ok {
  659. return true
  660. }
  661. key := m.indexKey(name)
  662. err := m.pool.WithClient(func(c *KVClient) error {
  663. _, err := c.Read(key)
  664. return err
  665. })
  666. return err == nil
  667. }
  668. // GetIndex retrieves an index by name.
  669. func (m *SchemaManager) GetIndex(name string) (*Index, error) {
  670. m.mu.Lock()
  671. defer m.mu.Unlock()
  672. cacheKey := strings.ToLower(name)
  673. if index, ok := m.indexCache[cacheKey]; ok {
  674. return cloneIndex(index), nil
  675. }
  676. key := m.indexKey(name)
  677. var data string
  678. err := m.pool.WithClient(func(c *KVClient) error {
  679. var err error
  680. data, err = c.Read(key)
  681. return err
  682. })
  683. if err != nil {
  684. if err == ErrKeyNotFound {
  685. return nil, fmt.Errorf("%w: %s", ErrIndexNotFound, name)
  686. }
  687. return nil, err
  688. }
  689. var index Index
  690. if err := json.Unmarshal([]byte(data), &index); err != nil {
  691. return nil, fmt.Errorf("failed to parse index: %w", err)
  692. }
  693. m.indexCache[cacheKey] = &index
  694. return cloneIndex(&index), nil
  695. }
  696. // ListIndexes returns all index names.
  697. func (m *SchemaManager) ListIndexes() ([]string, error) {
  698. m.mu.Lock()
  699. defer m.mu.Unlock()
  700. if m.indexListCached {
  701. return append([]string(nil), m.indexListCache...), nil
  702. }
  703. key := m.indexListKey()
  704. var data string
  705. err := m.pool.WithClient(func(c *KVClient) error {
  706. var err error
  707. data, err = c.Read(key)
  708. return err
  709. })
  710. if err == ErrKeyNotFound {
  711. m.indexListCache = nil
  712. m.indexListCached = true
  713. return []string{}, nil
  714. }
  715. if err != nil {
  716. return nil, err
  717. }
  718. var indexes []string
  719. if err := json.Unmarshal([]byte(data), &indexes); err != nil {
  720. return nil, fmt.Errorf("failed to parse index list: %w", err)
  721. }
  722. m.indexListCache = append([]string(nil), indexes...)
  723. m.indexListCached = true
  724. return indexes, nil
  725. }
  726. // ListTableIndexes returns all indexes for a table.
  727. func (m *SchemaManager) ListTableIndexes(table string) ([]*Index, error) {
  728. indexes, err := m.ListIndexes()
  729. if err != nil {
  730. return nil, err
  731. }
  732. var result []*Index
  733. for _, name := range indexes {
  734. idx, err := m.GetIndex(name)
  735. if err != nil {
  736. // An index dropped concurrently is simply absent; any other error
  737. // (storage/IO or corrupt data) must not be silently swallowed.
  738. if errors.Is(err, ErrIndexNotFound) {
  739. continue
  740. }
  741. return nil, err
  742. }
  743. if strings.EqualFold(idx.Table, table) {
  744. result = append(result, idx)
  745. }
  746. }
  747. return result, nil
  748. }
  749. // addToIndexList adds an index name to the list.
  750. func (m *SchemaManager) addToIndexList(name string) error {
  751. key := m.indexListKey()
  752. var indexes []string
  753. var data string
  754. err := m.pool.WithClient(func(c *KVClient) error {
  755. var err error
  756. data, err = c.Read(key)
  757. return err
  758. })
  759. if err == nil {
  760. json.Unmarshal([]byte(data), &indexes)
  761. }
  762. indexes = append(indexes, name)
  763. newData, _ := json.Marshal(indexes)
  764. err = m.pool.WithClient(func(c *KVClient) error {
  765. return c.Write(key, string(newData))
  766. })
  767. if err == nil {
  768. m.indexListCache = append([]string(nil), indexes...)
  769. m.indexListCached = true
  770. }
  771. return err
  772. }
  773. // removeFromIndexList removes an index name from the list.
  774. func (m *SchemaManager) removeFromIndexList(name string) error {
  775. key := m.indexListKey()
  776. var indexes []string
  777. var data string
  778. err := m.pool.WithClient(func(c *KVClient) error {
  779. var err error
  780. data, err = c.Read(key)
  781. return err
  782. })
  783. if err != nil {
  784. return nil
  785. }
  786. json.Unmarshal([]byte(data), &indexes)
  787. var newIndexes []string
  788. for _, idx := range indexes {
  789. if !strings.EqualFold(idx, name) {
  790. newIndexes = append(newIndexes, idx)
  791. }
  792. }
  793. newData, _ := json.Marshal(newIndexes)
  794. err = m.pool.WithClient(func(c *KVClient) error {
  795. return c.Write(key, string(newData))
  796. })
  797. if err == nil {
  798. m.indexListCache = append([]string(nil), newIndexes...)
  799. m.indexListCached = true
  800. }
  801. return err
  802. }
  803. // AddColumn adds a new column to a table.
  804. func (m *SchemaManager) AddColumn(table string, column Column) error {
  805. m.mu.Lock()
  806. defer m.mu.Unlock()
  807. schema, err := m.getSchemaUnsafe(table)
  808. if err != nil {
  809. return err
  810. }
  811. // Check if column already exists
  812. for _, col := range schema.Columns {
  813. if strings.EqualFold(col.Name, column.Name) {
  814. return fmt.Errorf("column already exists: %s", column.Name)
  815. }
  816. }
  817. // Publish a fresh snapshot instead of mutating readers' shared pointer.
  818. schema = cloneSchema(schema)
  819. schema.Columns = append(schema.Columns, column)
  820. // Update schema
  821. return m.updateSchemaUnsafe(schema)
  822. }
  823. // DropColumn removes a column from a table.
  824. func (m *SchemaManager) DropColumn(table, columnName string) error {
  825. m.mu.Lock()
  826. defer m.mu.Unlock()
  827. schema, err := m.getSchemaUnsafe(table)
  828. if err != nil {
  829. return err
  830. }
  831. // Cannot drop primary key column
  832. if strings.EqualFold(schema.PrimaryKey, columnName) {
  833. return fmt.Errorf("cannot drop primary key column: %s", columnName)
  834. }
  835. // Find and remove column
  836. newColumns := make([]Column, 0, len(schema.Columns)-1)
  837. found := false
  838. for _, col := range schema.Columns {
  839. if strings.EqualFold(col.Name, columnName) {
  840. found = true
  841. continue
  842. }
  843. newColumns = append(newColumns, col)
  844. }
  845. if !found {
  846. return fmt.Errorf("column not found: %s", columnName)
  847. }
  848. schema = cloneSchema(schema)
  849. schema.Columns = newColumns
  850. // Update schema
  851. return m.updateSchemaUnsafe(schema)
  852. }
  853. // RenameTable renames a table.
  854. func (m *SchemaManager) RenameTable(oldName, newName string) error {
  855. m.mu.Lock()
  856. defer m.mu.Unlock()
  857. // Check if old table exists
  858. schema, err := m.getSchemaUnsafe(oldName)
  859. if err != nil {
  860. return err
  861. }
  862. // Check if new table name already exists
  863. _, err = m.getSchemaUnsafe(newName)
  864. if err == nil {
  865. return fmt.Errorf("table already exists: %s", newName)
  866. }
  867. schema = cloneSchema(schema)
  868. // Update schema name
  869. schema.Name = newName
  870. rowIDKey := m.rowIDKey(oldName)
  871. // Delete old schema
  872. oldKey := m.schemaKey(oldName)
  873. err = m.pool.WithClient(func(c *KVClient) error {
  874. return c.Delete(oldKey)
  875. })
  876. if err != nil {
  877. return err
  878. }
  879. // Remove from catalog
  880. m.removeFromCatalog(oldName)
  881. // Move ROWID state.
  882. m.pool.WithClient(func(c *KVClient) error {
  883. return c.Delete(rowIDKey)
  884. })
  885. // Update cache
  886. oldLower := strings.ToLower(oldName)
  887. newLower := strings.ToLower(newName)
  888. delete(m.cache, oldLower)
  889. m.rowIDMu.Lock()
  890. delete(m.rowIDAlloc, oldLower)
  891. m.rowIDMu.Unlock()
  892. // Write new schema
  893. newKey := m.schemaKey(newName)
  894. data, _ := json.Marshal(schema)
  895. err = m.pool.WithClient(func(c *KVClient) error {
  896. return c.Write(newKey, string(data))
  897. })
  898. if err != nil {
  899. return err
  900. }
  901. // Add to catalog
  902. m.addToCatalog(newName)
  903. // Update cache
  904. m.cache[newLower] = schema
  905. m.bumpVersionLocked()
  906. return nil
  907. }
  908. // RenameColumn renames a column in a table.
  909. func (m *SchemaManager) RenameColumn(table, oldName, newName string) error {
  910. m.mu.Lock()
  911. defer m.mu.Unlock()
  912. schema, err := m.getSchemaUnsafe(table)
  913. if err != nil {
  914. return err
  915. }
  916. // Check if new column name already exists
  917. for _, col := range schema.Columns {
  918. if strings.EqualFold(col.Name, newName) {
  919. return fmt.Errorf("column already exists: %s", newName)
  920. }
  921. }
  922. schema = cloneSchema(schema)
  923. // Find and rename column
  924. found := false
  925. for i, col := range schema.Columns {
  926. if strings.EqualFold(col.Name, oldName) {
  927. schema.Columns[i].Name = newName
  928. found = true
  929. // Update primary key reference if needed
  930. if strings.EqualFold(schema.PrimaryKey, oldName) {
  931. schema.PrimaryKey = newName
  932. }
  933. break
  934. }
  935. }
  936. if !found {
  937. return fmt.Errorf("column not found: %s", oldName)
  938. }
  939. // Update schema
  940. return m.updateSchemaUnsafe(schema)
  941. }
  942. // getSchemaUnsafe gets a schema without locking (internal use).
  943. func (m *SchemaManager) getSchemaUnsafe(table string) (*Schema, error) {
  944. tableLower := strings.ToLower(table)
  945. // Check cache
  946. if schema, ok := m.cache[tableLower]; ok {
  947. return schema, nil
  948. }
  949. // Read from storage
  950. key := m.schemaKey(table)
  951. var data string
  952. err := m.pool.WithClient(func(c *KVClient) error {
  953. var err error
  954. data, err = c.Read(key)
  955. return err
  956. })
  957. if err != nil {
  958. return nil, fmt.Errorf("table not found: %s", table)
  959. }
  960. var schema Schema
  961. if err := json.Unmarshal([]byte(data), &schema); err != nil {
  962. return nil, err
  963. }
  964. m.cache[tableLower] = &schema
  965. return &schema, nil
  966. }
  967. // updateSchemaUnsafe updates a schema without locking (internal use).
  968. func (m *SchemaManager) updateSchemaUnsafe(schema *Schema) error {
  969. key := m.schemaKey(schema.Name)
  970. data, _ := json.Marshal(schema)
  971. err := m.pool.WithClient(func(c *KVClient) error {
  972. return c.Write(key, string(data))
  973. })
  974. if err != nil {
  975. return err
  976. }
  977. // Update cache
  978. m.cache[strings.ToLower(schema.Name)] = schema
  979. m.bumpVersionLocked()
  980. return nil
  981. }