schema.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  1. package storage
  2. import (
  3. "fmt"
  4. "strings"
  5. "sync"
  6. "time"
  7. "github.com/goccy/go-json"
  8. "github.com/danfragoso/pizzasql-next/pkg/analyzer"
  9. )
  10. // Schema represents a table schema.
  11. type Schema struct {
  12. Name string `json:"name"`
  13. Columns []Column `json:"columns"`
  14. PrimaryKey string `json:"primary_key"`
  15. CreatedAt time.Time `json:"created_at"`
  16. NextRowID int64 `json:"next_rowid"`
  17. AutoIncrement bool `json:"autoincrement"`
  18. }
  19. // Column represents a column definition.
  20. type Column struct {
  21. Name string `json:"name"`
  22. Type string `json:"type"`
  23. Nullable bool `json:"nullable"`
  24. Default interface{} `json:"default,omitempty"`
  25. PrimaryKey bool `json:"primary_key"`
  26. }
  27. // Index represents an index definition.
  28. type Index struct {
  29. Name string `json:"name"`
  30. Table string `json:"table"`
  31. Columns []IndexColumn `json:"columns"`
  32. Unique bool `json:"unique"`
  33. CreatedAt time.Time `json:"created_at"`
  34. }
  35. // IndexColumn represents a column in an index.
  36. type IndexColumn struct {
  37. Name string `json:"name"`
  38. Desc bool `json:"desc"`
  39. }
  40. // SchemaManager manages table schemas.
  41. type SchemaManager struct {
  42. pool *KVPool
  43. database string
  44. cache map[string]*Schema
  45. rowIDInitialized map[string]bool
  46. version uint64
  47. mu sync.RWMutex
  48. }
  49. // NewSchemaManager creates a new schema manager.
  50. func NewSchemaManager(pool *KVPool, database string) *SchemaManager {
  51. return &SchemaManager{
  52. pool: pool,
  53. database: database,
  54. cache: make(map[string]*Schema),
  55. rowIDInitialized: make(map[string]bool),
  56. }
  57. }
  58. // GetDatabaseName returns the database name.
  59. func (m *SchemaManager) GetDatabaseName() string {
  60. return m.database
  61. }
  62. // GetPool returns the KV pool.
  63. func (m *SchemaManager) GetPool() *KVPool {
  64. return m.pool
  65. }
  66. // Version returns the in-process schema catalog version. It is incremented for
  67. // schema/index definition changes so cached executors can resync their analyzer
  68. // catalogs without scanning storage on every query.
  69. func (m *SchemaManager) Version() uint64 {
  70. m.mu.RLock()
  71. defer m.mu.RUnlock()
  72. return m.version
  73. }
  74. func (m *SchemaManager) bumpVersionLocked() {
  75. m.version++
  76. }
  77. // schemaKey returns the key for a table schema.
  78. func (m *SchemaManager) schemaKey(table string) string {
  79. return fmt.Sprintf("%s:_schema:%s", m.database, strings.ToLower(table))
  80. }
  81. // catalogKey returns the key for the table catalog.
  82. func (m *SchemaManager) catalogKey() string {
  83. return fmt.Sprintf("%s:_sys:tables", m.database)
  84. }
  85. // rowIDKey returns the key for a table's next ROWID counter.
  86. func (m *SchemaManager) rowIDKey(table string) string {
  87. return fmt.Sprintf("%s:_sys:rowid:%s", m.database, strings.ToLower(table))
  88. }
  89. // CreateTable creates a new table.
  90. func (m *SchemaManager) CreateTable(schema *Schema) error {
  91. m.mu.Lock()
  92. defer m.mu.Unlock()
  93. // Check if table already exists
  94. key := m.schemaKey(schema.Name)
  95. err := m.pool.WithClient(func(c *KVClient) error {
  96. _, err := c.Read(key)
  97. return err
  98. })
  99. if err == nil {
  100. return fmt.Errorf("table already exists: %s", schema.Name)
  101. }
  102. // Set creation time
  103. schema.CreatedAt = time.Now()
  104. // Determine primary key if not set
  105. if schema.PrimaryKey == "" {
  106. for _, col := range schema.Columns {
  107. if col.PrimaryKey {
  108. schema.PrimaryKey = col.Name
  109. break
  110. }
  111. }
  112. // No explicit primary key declared — use synthetic _rowid_ so user
  113. // columns remain unconstrained and can hold duplicate or NULL values.
  114. if schema.PrimaryKey == "" {
  115. schema.PrimaryKey = "_rowid_"
  116. }
  117. }
  118. // Serialize schema
  119. data, err := json.Marshal(schema)
  120. if err != nil {
  121. return fmt.Errorf("failed to serialize schema: %w", err)
  122. }
  123. // Write schema
  124. err = m.pool.WithClient(func(c *KVClient) error {
  125. return c.Write(key, string(data))
  126. })
  127. if err != nil {
  128. return fmt.Errorf("failed to write schema: %w", err)
  129. }
  130. // Update catalog
  131. if err := m.addToCatalog(schema.Name); err != nil {
  132. // Rollback schema write
  133. m.pool.WithClient(func(c *KVClient) error {
  134. return c.Delete(key)
  135. })
  136. return err
  137. }
  138. // Update cache
  139. m.cache[strings.ToLower(schema.Name)] = schema
  140. m.bumpVersionLocked()
  141. return nil
  142. }
  143. // DropTable drops a table.
  144. func (m *SchemaManager) DropTable(name string) error {
  145. m.mu.Lock()
  146. defer m.mu.Unlock()
  147. key := m.schemaKey(name)
  148. // Check if table exists
  149. err := m.pool.WithClient(func(c *KVClient) error {
  150. _, err := c.Read(key)
  151. return err
  152. })
  153. if err != nil {
  154. return fmt.Errorf("table not found: %s", name)
  155. }
  156. // Delete all rows
  157. dataPrefix := fmt.Sprintf("%s:_data:%s:", m.database, strings.ToLower(name))
  158. err = m.pool.WithClient(func(c *KVClient) error {
  159. // Get all keys with this prefix and delete them
  160. // Note: This is a simplified version - in production you'd want batch delete
  161. values, err := c.Reads(dataPrefix)
  162. if err != nil {
  163. return err
  164. }
  165. // The Reads command returns values, not keys, so we can't delete them directly
  166. // In a real implementation, we'd need a keys scan command
  167. _ = values
  168. return nil
  169. })
  170. // Delete schema
  171. err = m.pool.WithClient(func(c *KVClient) error {
  172. return c.Delete(key)
  173. })
  174. if err != nil {
  175. return fmt.Errorf("failed to delete schema: %w", err)
  176. }
  177. // Delete ROWID state.
  178. m.pool.WithClient(func(c *KVClient) error {
  179. return c.Delete(m.rowIDKey(name))
  180. })
  181. // Update catalog
  182. if err := m.removeFromCatalog(name); err != nil {
  183. return err
  184. }
  185. // Update cache
  186. tableLower := strings.ToLower(name)
  187. delete(m.cache, tableLower)
  188. delete(m.rowIDInitialized, tableLower)
  189. m.bumpVersionLocked()
  190. return nil
  191. }
  192. // GetSchema retrieves a table schema.
  193. func (m *SchemaManager) GetSchema(name string) (*Schema, error) {
  194. m.mu.RLock()
  195. if schema, ok := m.cache[strings.ToLower(name)]; ok {
  196. m.mu.RUnlock()
  197. return schema, nil
  198. }
  199. m.mu.RUnlock()
  200. m.mu.Lock()
  201. defer m.mu.Unlock()
  202. // Double-check after acquiring write lock
  203. if schema, ok := m.cache[strings.ToLower(name)]; ok {
  204. return schema, nil
  205. }
  206. key := m.schemaKey(name)
  207. var data string
  208. err := m.pool.WithClient(func(c *KVClient) error {
  209. var err error
  210. data, err = c.Read(key)
  211. return err
  212. })
  213. if err != nil {
  214. if err == ErrKeyNotFound {
  215. return nil, fmt.Errorf("table not found: %s", name)
  216. }
  217. return nil, err
  218. }
  219. var schema Schema
  220. if err := json.Unmarshal([]byte(data), &schema); err != nil {
  221. return nil, fmt.Errorf("failed to parse schema: %w", err)
  222. }
  223. m.cache[strings.ToLower(name)] = &schema
  224. return &schema, nil
  225. }
  226. // TableExists checks if a table exists.
  227. func (m *SchemaManager) TableExists(name string) bool {
  228. _, err := m.GetSchema(name)
  229. return err == nil
  230. }
  231. // ListTables returns all table names.
  232. func (m *SchemaManager) ListTables() ([]string, error) {
  233. var data string
  234. err := m.pool.WithClient(func(c *KVClient) error {
  235. var err error
  236. data, err = c.Read(m.catalogKey())
  237. return err
  238. })
  239. if err != nil {
  240. if err == ErrKeyNotFound {
  241. return nil, nil
  242. }
  243. return nil, err
  244. }
  245. var tables []string
  246. if err := json.Unmarshal([]byte(data), &tables); err != nil {
  247. return nil, fmt.Errorf("failed to parse catalog: %w", err)
  248. }
  249. return tables, nil
  250. }
  251. // addToCatalog adds a table to the catalog.
  252. func (m *SchemaManager) addToCatalog(name string) error {
  253. tables, err := m.ListTables()
  254. if err != nil && err != ErrKeyNotFound {
  255. return err
  256. }
  257. // Check if already exists
  258. lowerName := strings.ToLower(name)
  259. for _, t := range tables {
  260. if strings.ToLower(t) == lowerName {
  261. return nil
  262. }
  263. }
  264. tables = append(tables, name)
  265. data, err := json.Marshal(tables)
  266. if err != nil {
  267. return err
  268. }
  269. return m.pool.WithClient(func(c *KVClient) error {
  270. return c.Write(m.catalogKey(), string(data))
  271. })
  272. }
  273. // removeFromCatalog removes a table from the catalog.
  274. func (m *SchemaManager) removeFromCatalog(name string) error {
  275. tables, err := m.ListTables()
  276. if err != nil {
  277. return err
  278. }
  279. lowerName := strings.ToLower(name)
  280. newTables := make([]string, 0, len(tables))
  281. for _, t := range tables {
  282. if strings.ToLower(t) != lowerName {
  283. newTables = append(newTables, t)
  284. }
  285. }
  286. data, err := json.Marshal(newTables)
  287. if err != nil {
  288. return err
  289. }
  290. return m.pool.WithClient(func(c *KVClient) error {
  291. return c.Write(m.catalogKey(), string(data))
  292. })
  293. }
  294. // InvalidateCache clears the cache for a table.
  295. func (m *SchemaManager) InvalidateCache(name string) {
  296. m.mu.Lock()
  297. defer m.mu.Unlock()
  298. tableLower := strings.ToLower(name)
  299. delete(m.cache, tableLower)
  300. delete(m.rowIDInitialized, tableLower)
  301. }
  302. // ToAnalyzerTableInfo converts a Schema to analyzer.TableInfo.
  303. func (s *Schema) ToAnalyzerTableInfo() *analyzer.TableInfo {
  304. info := &analyzer.TableInfo{
  305. Name: s.Name,
  306. }
  307. for _, col := range s.Columns {
  308. info.Columns = append(info.Columns, analyzer.ColumnInfo{
  309. Name: col.Name,
  310. Type: analyzer.TypeFromName(col.Type),
  311. Nullable: col.Nullable,
  312. PrimaryKey: col.PrimaryKey,
  313. TableName: s.Name,
  314. })
  315. }
  316. return info
  317. }
  318. // GetColumn returns a column by name.
  319. func (s *Schema) GetColumn(name string) (*Column, bool) {
  320. lowerName := strings.ToLower(name)
  321. for i := range s.Columns {
  322. if strings.ToLower(s.Columns[i].Name) == lowerName {
  323. return &s.Columns[i], true
  324. }
  325. }
  326. return nil, false
  327. }
  328. // GetNextRowID gets and increments the next ROWID for a table.
  329. func (m *SchemaManager) GetNextRowID(table string) (int64, error) {
  330. m.mu.Lock()
  331. defer m.mu.Unlock()
  332. schema, err := m.getSchemaLocked(table)
  333. if err != nil {
  334. return 0, err
  335. }
  336. nextRowID, err := m.getNextRowIDLocked(schema)
  337. if err != nil {
  338. return 0, err
  339. }
  340. schema.NextRowID = nextRowID + 1
  341. return nextRowID, nil
  342. }
  343. // UpdateMaxRowID updates the next ROWID if the provided value is higher.
  344. func (m *SchemaManager) UpdateMaxRowID(table string, rowid int64) error {
  345. m.mu.Lock()
  346. defer m.mu.Unlock()
  347. schema, err := m.getSchemaLocked(table)
  348. if err != nil {
  349. return err
  350. }
  351. nextRowID, err := m.getNextRowIDLocked(schema)
  352. if err != nil {
  353. return err
  354. }
  355. if rowid >= nextRowID {
  356. schema.NextRowID = rowid + 1
  357. }
  358. return nil
  359. }
  360. // getNextRowIDLocked returns a table's in-memory ROWID counter (must hold lock).
  361. // On first use after startup, the counter is derived from durable row data so
  362. // ROWID movement does not add a separate WAL entry.
  363. func (m *SchemaManager) getNextRowIDLocked(schema *Schema) (int64, error) {
  364. tableLower := strings.ToLower(schema.Name)
  365. if m.rowIDInitialized[tableLower] {
  366. if schema.NextRowID < 1 {
  367. schema.NextRowID = 1
  368. }
  369. return schema.NextRowID, nil
  370. }
  371. nextRowID, err := m.deriveNextRowIDLocked(schema)
  372. if err != nil {
  373. return 0, err
  374. }
  375. if schema.NextRowID > nextRowID {
  376. nextRowID = schema.NextRowID
  377. }
  378. if nextRowID < 1 {
  379. nextRowID = 1
  380. }
  381. schema.NextRowID = nextRowID
  382. m.rowIDInitialized[tableLower] = true
  383. return schema.NextRowID, nil
  384. }
  385. // deriveNextRowIDLocked scans durable row values to recover max(rowid)+1.
  386. func (m *SchemaManager) deriveNextRowIDLocked(schema *Schema) (int64, error) {
  387. prefix := fmt.Sprintf("%s:_data:%s:", m.database, strings.ToLower(schema.Name))
  388. var values []string
  389. err := m.pool.WithClient(func(c *KVClient) error {
  390. var err error
  391. values, err = c.Reads(prefix)
  392. return err
  393. })
  394. if err != nil {
  395. return 0, err
  396. }
  397. var maxRowID int64
  398. for _, value := range values {
  399. var row Row
  400. if err := json.Unmarshal([]byte(value), &row); err != nil {
  401. return 0, fmt.Errorf("failed to parse row while deriving ROWID: %w", err)
  402. }
  403. if rowid, ok := valueAsInt64(row["_rowid_"]); ok && rowid > maxRowID {
  404. maxRowID = rowid
  405. }
  406. }
  407. return maxRowID + 1, nil
  408. }
  409. func valueAsInt64(value interface{}) (int64, bool) {
  410. switch v := value.(type) {
  411. case int64:
  412. return v, true
  413. case int:
  414. return int64(v), true
  415. case float64:
  416. return int64(v), true
  417. default:
  418. return 0, false
  419. }
  420. }
  421. // getSchemaLocked retrieves schema (must hold lock).
  422. func (m *SchemaManager) getSchemaLocked(name string) (*Schema, error) {
  423. if schema, ok := m.cache[strings.ToLower(name)]; ok {
  424. return schema, nil
  425. }
  426. key := m.schemaKey(name)
  427. var data string
  428. err := m.pool.WithClient(func(c *KVClient) error {
  429. var err error
  430. data, err = c.Read(key)
  431. return err
  432. })
  433. if err != nil {
  434. if err == ErrKeyNotFound {
  435. return nil, fmt.Errorf("table not found: %s", name)
  436. }
  437. return nil, err
  438. }
  439. var schema Schema
  440. if err := json.Unmarshal([]byte(data), &schema); err != nil {
  441. return nil, fmt.Errorf("failed to parse schema: %w", err)
  442. }
  443. m.cache[strings.ToLower(name)] = &schema
  444. return &schema, nil
  445. }
  446. // saveSchemaLocked saves schema (must hold lock).
  447. func (m *SchemaManager) saveSchemaLocked(schema *Schema) error {
  448. data, err := json.Marshal(schema)
  449. if err != nil {
  450. return fmt.Errorf("failed to serialize schema: %w", err)
  451. }
  452. key := m.schemaKey(schema.Name)
  453. err = m.pool.WithClient(func(c *KVClient) error {
  454. return c.Write(key, string(data))
  455. })
  456. if err != nil {
  457. return fmt.Errorf("failed to write schema: %w", err)
  458. }
  459. m.cache[strings.ToLower(schema.Name)] = schema
  460. return nil
  461. }
  462. // Index management methods
  463. // indexKey returns the key for an index.
  464. func (m *SchemaManager) indexKey(name string) string {
  465. return fmt.Sprintf("%s:index:%s", m.database, strings.ToLower(name))
  466. }
  467. // indexListKey returns the key for the index list.
  468. func (m *SchemaManager) indexListKey() string {
  469. return fmt.Sprintf("%s:indexes", m.database)
  470. }
  471. // CreateIndex creates a new index.
  472. func (m *SchemaManager) CreateIndex(index *Index) error {
  473. m.mu.Lock()
  474. defer m.mu.Unlock()
  475. // Check if index already exists
  476. key := m.indexKey(index.Name)
  477. err := m.pool.WithClient(func(c *KVClient) error {
  478. _, err := c.Read(key)
  479. return err
  480. })
  481. if err == nil {
  482. return fmt.Errorf("index already exists: %s", index.Name)
  483. }
  484. // Verify table exists
  485. if _, err := m.getSchemaLocked(index.Table); err != nil {
  486. return fmt.Errorf("table not found: %s", index.Table)
  487. }
  488. // Save index
  489. index.CreatedAt = time.Now()
  490. data, err := json.Marshal(index)
  491. if err != nil {
  492. return fmt.Errorf("failed to serialize index: %w", err)
  493. }
  494. err = m.pool.WithClient(func(c *KVClient) error {
  495. return c.Write(key, string(data))
  496. })
  497. if err != nil {
  498. return fmt.Errorf("failed to write index: %w", err)
  499. }
  500. // Add to index list
  501. if err := m.addToIndexList(index.Name); err != nil {
  502. return err
  503. }
  504. m.bumpVersionLocked()
  505. return nil
  506. }
  507. // DropIndex drops an index.
  508. func (m *SchemaManager) DropIndex(name string) error {
  509. m.mu.Lock()
  510. defer m.mu.Unlock()
  511. key := m.indexKey(name)
  512. err := m.pool.WithClient(func(c *KVClient) error {
  513. return c.Delete(key)
  514. })
  515. if err != nil {
  516. return fmt.Errorf("failed to delete index: %w", err)
  517. }
  518. if err := m.removeFromIndexList(name); err != nil {
  519. return err
  520. }
  521. m.bumpVersionLocked()
  522. return nil
  523. }
  524. // IndexExists checks if an index exists.
  525. func (m *SchemaManager) IndexExists(name string) bool {
  526. m.mu.RLock()
  527. defer m.mu.RUnlock()
  528. key := m.indexKey(name)
  529. err := m.pool.WithClient(func(c *KVClient) error {
  530. _, err := c.Read(key)
  531. return err
  532. })
  533. return err == nil
  534. }
  535. // GetIndex retrieves an index by name.
  536. func (m *SchemaManager) GetIndex(name string) (*Index, error) {
  537. m.mu.RLock()
  538. defer m.mu.RUnlock()
  539. key := m.indexKey(name)
  540. var data string
  541. err := m.pool.WithClient(func(c *KVClient) error {
  542. var err error
  543. data, err = c.Read(key)
  544. return err
  545. })
  546. if err != nil {
  547. return nil, fmt.Errorf("index not found: %s", name)
  548. }
  549. var index Index
  550. if err := json.Unmarshal([]byte(data), &index); err != nil {
  551. return nil, fmt.Errorf("failed to parse index: %w", err)
  552. }
  553. return &index, nil
  554. }
  555. // ListIndexes returns all index names.
  556. func (m *SchemaManager) ListIndexes() ([]string, error) {
  557. m.mu.RLock()
  558. defer m.mu.RUnlock()
  559. key := m.indexListKey()
  560. var data string
  561. err := m.pool.WithClient(func(c *KVClient) error {
  562. var err error
  563. data, err = c.Read(key)
  564. return err
  565. })
  566. if err != nil {
  567. return []string{}, nil
  568. }
  569. var indexes []string
  570. if err := json.Unmarshal([]byte(data), &indexes); err != nil {
  571. return []string{}, nil
  572. }
  573. return indexes, nil
  574. }
  575. // ListTableIndexes returns all indexes for a table.
  576. func (m *SchemaManager) ListTableIndexes(table string) ([]*Index, error) {
  577. indexes, err := m.ListIndexes()
  578. if err != nil {
  579. return nil, err
  580. }
  581. var result []*Index
  582. for _, name := range indexes {
  583. idx, err := m.GetIndex(name)
  584. if err != nil {
  585. continue
  586. }
  587. if strings.EqualFold(idx.Table, table) {
  588. result = append(result, idx)
  589. }
  590. }
  591. return result, nil
  592. }
  593. // addToIndexList adds an index name to the list.
  594. func (m *SchemaManager) addToIndexList(name string) error {
  595. key := m.indexListKey()
  596. var indexes []string
  597. var data string
  598. err := m.pool.WithClient(func(c *KVClient) error {
  599. var err error
  600. data, err = c.Read(key)
  601. return err
  602. })
  603. if err == nil {
  604. json.Unmarshal([]byte(data), &indexes)
  605. }
  606. indexes = append(indexes, name)
  607. newData, _ := json.Marshal(indexes)
  608. return m.pool.WithClient(func(c *KVClient) error {
  609. return c.Write(key, string(newData))
  610. })
  611. }
  612. // removeFromIndexList removes an index name from the list.
  613. func (m *SchemaManager) removeFromIndexList(name string) error {
  614. key := m.indexListKey()
  615. var indexes []string
  616. var data string
  617. err := m.pool.WithClient(func(c *KVClient) error {
  618. var err error
  619. data, err = c.Read(key)
  620. return err
  621. })
  622. if err != nil {
  623. return nil
  624. }
  625. json.Unmarshal([]byte(data), &indexes)
  626. var newIndexes []string
  627. for _, idx := range indexes {
  628. if !strings.EqualFold(idx, name) {
  629. newIndexes = append(newIndexes, idx)
  630. }
  631. }
  632. newData, _ := json.Marshal(newIndexes)
  633. return m.pool.WithClient(func(c *KVClient) error {
  634. return c.Write(key, string(newData))
  635. })
  636. }
  637. // AddColumn adds a new column to a table.
  638. func (m *SchemaManager) AddColumn(table string, column Column) error {
  639. m.mu.Lock()
  640. defer m.mu.Unlock()
  641. schema, err := m.getSchemaUnsafe(table)
  642. if err != nil {
  643. return err
  644. }
  645. // Check if column already exists
  646. for _, col := range schema.Columns {
  647. if strings.EqualFold(col.Name, column.Name) {
  648. return fmt.Errorf("column already exists: %s", column.Name)
  649. }
  650. }
  651. // Add column
  652. schema.Columns = append(schema.Columns, column)
  653. // Update schema
  654. return m.updateSchemaUnsafe(schema)
  655. }
  656. // DropColumn removes a column from a table.
  657. func (m *SchemaManager) DropColumn(table, columnName string) error {
  658. m.mu.Lock()
  659. defer m.mu.Unlock()
  660. schema, err := m.getSchemaUnsafe(table)
  661. if err != nil {
  662. return err
  663. }
  664. // Cannot drop primary key column
  665. if strings.EqualFold(schema.PrimaryKey, columnName) {
  666. return fmt.Errorf("cannot drop primary key column: %s", columnName)
  667. }
  668. // Find and remove column
  669. newColumns := make([]Column, 0, len(schema.Columns)-1)
  670. found := false
  671. for _, col := range schema.Columns {
  672. if strings.EqualFold(col.Name, columnName) {
  673. found = true
  674. continue
  675. }
  676. newColumns = append(newColumns, col)
  677. }
  678. if !found {
  679. return fmt.Errorf("column not found: %s", columnName)
  680. }
  681. schema.Columns = newColumns
  682. // Update schema
  683. return m.updateSchemaUnsafe(schema)
  684. }
  685. // RenameTable renames a table.
  686. func (m *SchemaManager) RenameTable(oldName, newName string) error {
  687. m.mu.Lock()
  688. defer m.mu.Unlock()
  689. // Check if old table exists
  690. schema, err := m.getSchemaUnsafe(oldName)
  691. if err != nil {
  692. return err
  693. }
  694. // Check if new table name already exists
  695. _, err = m.getSchemaUnsafe(newName)
  696. if err == nil {
  697. return fmt.Errorf("table already exists: %s", newName)
  698. }
  699. // Update schema name
  700. schema.Name = newName
  701. rowIDKey := m.rowIDKey(oldName)
  702. // Delete old schema
  703. oldKey := m.schemaKey(oldName)
  704. err = m.pool.WithClient(func(c *KVClient) error {
  705. return c.Delete(oldKey)
  706. })
  707. if err != nil {
  708. return err
  709. }
  710. // Remove from catalog
  711. m.removeFromCatalog(oldName)
  712. // Move ROWID state.
  713. m.pool.WithClient(func(c *KVClient) error {
  714. return c.Delete(rowIDKey)
  715. })
  716. // Update cache
  717. oldLower := strings.ToLower(oldName)
  718. newLower := strings.ToLower(newName)
  719. wasInitialized := m.rowIDInitialized[oldLower]
  720. delete(m.cache, oldLower)
  721. delete(m.rowIDInitialized, oldLower)
  722. // Write new schema
  723. newKey := m.schemaKey(newName)
  724. data, _ := json.Marshal(schema)
  725. err = m.pool.WithClient(func(c *KVClient) error {
  726. return c.Write(newKey, string(data))
  727. })
  728. if err != nil {
  729. return err
  730. }
  731. // Add to catalog
  732. m.addToCatalog(newName)
  733. // Update cache
  734. m.cache[newLower] = schema
  735. if wasInitialized {
  736. m.rowIDInitialized[newLower] = true
  737. }
  738. m.bumpVersionLocked()
  739. return nil
  740. }
  741. // RenameColumn renames a column in a table.
  742. func (m *SchemaManager) RenameColumn(table, oldName, newName string) error {
  743. m.mu.Lock()
  744. defer m.mu.Unlock()
  745. schema, err := m.getSchemaUnsafe(table)
  746. if err != nil {
  747. return err
  748. }
  749. // Check if new column name already exists
  750. for _, col := range schema.Columns {
  751. if strings.EqualFold(col.Name, newName) {
  752. return fmt.Errorf("column already exists: %s", newName)
  753. }
  754. }
  755. // Find and rename column
  756. found := false
  757. for i, col := range schema.Columns {
  758. if strings.EqualFold(col.Name, oldName) {
  759. schema.Columns[i].Name = newName
  760. found = true
  761. // Update primary key reference if needed
  762. if strings.EqualFold(schema.PrimaryKey, oldName) {
  763. schema.PrimaryKey = newName
  764. }
  765. break
  766. }
  767. }
  768. if !found {
  769. return fmt.Errorf("column not found: %s", oldName)
  770. }
  771. // Update schema
  772. return m.updateSchemaUnsafe(schema)
  773. }
  774. // getSchemaUnsafe gets a schema without locking (internal use).
  775. func (m *SchemaManager) getSchemaUnsafe(table string) (*Schema, error) {
  776. tableLower := strings.ToLower(table)
  777. // Check cache
  778. if schema, ok := m.cache[tableLower]; ok {
  779. return schema, nil
  780. }
  781. // Read from storage
  782. key := m.schemaKey(table)
  783. var data string
  784. err := m.pool.WithClient(func(c *KVClient) error {
  785. var err error
  786. data, err = c.Read(key)
  787. return err
  788. })
  789. if err != nil {
  790. return nil, fmt.Errorf("table not found: %s", table)
  791. }
  792. var schema Schema
  793. if err := json.Unmarshal([]byte(data), &schema); err != nil {
  794. return nil, err
  795. }
  796. m.cache[tableLower] = &schema
  797. return &schema, nil
  798. }
  799. // updateSchemaUnsafe updates a schema without locking (internal use).
  800. func (m *SchemaManager) updateSchemaUnsafe(schema *Schema) error {
  801. key := m.schemaKey(schema.Name)
  802. data, _ := json.Marshal(schema)
  803. err := m.pool.WithClient(func(c *KVClient) error {
  804. return c.Write(key, string(data))
  805. })
  806. if err != nil {
  807. return err
  808. }
  809. // Update cache
  810. m.cache[strings.ToLower(schema.Name)] = schema
  811. m.bumpVersionLocked()
  812. return nil
  813. }