2
0

schema.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843
  1. package storage
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "strings"
  6. "sync"
  7. "time"
  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. mu sync.RWMutex
  46. }
  47. // NewSchemaManager creates a new schema manager.
  48. func NewSchemaManager(pool *KVPool, database string) *SchemaManager {
  49. return &SchemaManager{
  50. pool: pool,
  51. database: database,
  52. cache: make(map[string]*Schema),
  53. }
  54. }
  55. // GetDatabaseName returns the database name.
  56. func (m *SchemaManager) GetDatabaseName() string {
  57. return m.database
  58. }
  59. // GetPool returns the KV pool.
  60. func (m *SchemaManager) GetPool() *KVPool {
  61. return m.pool
  62. }
  63. // schemaKey returns the key for a table schema.
  64. func (m *SchemaManager) schemaKey(table string) string {
  65. return fmt.Sprintf("%s:_schema:%s", m.database, strings.ToLower(table))
  66. }
  67. // catalogKey returns the key for the table catalog.
  68. func (m *SchemaManager) catalogKey() string {
  69. return fmt.Sprintf("%s:_sys:tables", m.database)
  70. }
  71. // CreateTable creates a new table.
  72. func (m *SchemaManager) CreateTable(schema *Schema) error {
  73. m.mu.Lock()
  74. defer m.mu.Unlock()
  75. // Check if table already exists
  76. key := m.schemaKey(schema.Name)
  77. err := m.pool.WithClient(func(c *KVClient) error {
  78. _, err := c.Read(key)
  79. return err
  80. })
  81. if err == nil {
  82. return fmt.Errorf("table already exists: %s", schema.Name)
  83. }
  84. // Set creation time
  85. schema.CreatedAt = time.Now()
  86. // Determine primary key if not set
  87. if schema.PrimaryKey == "" {
  88. for _, col := range schema.Columns {
  89. if col.PrimaryKey {
  90. schema.PrimaryKey = col.Name
  91. break
  92. }
  93. }
  94. // Default to first column if no primary key specified
  95. if schema.PrimaryKey == "" && len(schema.Columns) > 0 {
  96. schema.PrimaryKey = schema.Columns[0].Name
  97. schema.Columns[0].PrimaryKey = true
  98. }
  99. }
  100. // Serialize schema
  101. data, err := json.Marshal(schema)
  102. if err != nil {
  103. return fmt.Errorf("failed to serialize schema: %w", err)
  104. }
  105. // Write schema
  106. err = m.pool.WithClient(func(c *KVClient) error {
  107. return c.Write(key, string(data))
  108. })
  109. if err != nil {
  110. return fmt.Errorf("failed to write schema: %w", err)
  111. }
  112. // Update catalog
  113. if err := m.addToCatalog(schema.Name); err != nil {
  114. // Rollback schema write
  115. m.pool.WithClient(func(c *KVClient) error {
  116. return c.Delete(key)
  117. })
  118. return err
  119. }
  120. // Update cache
  121. m.cache[strings.ToLower(schema.Name)] = schema
  122. return nil
  123. }
  124. // DropTable drops a table.
  125. func (m *SchemaManager) DropTable(name string) error {
  126. m.mu.Lock()
  127. defer m.mu.Unlock()
  128. key := m.schemaKey(name)
  129. // Check if table exists
  130. err := m.pool.WithClient(func(c *KVClient) error {
  131. _, err := c.Read(key)
  132. return err
  133. })
  134. if err != nil {
  135. return fmt.Errorf("table not found: %s", name)
  136. }
  137. // Delete all rows
  138. dataPrefix := fmt.Sprintf("%s:_data:%s:", m.database, strings.ToLower(name))
  139. err = m.pool.WithClient(func(c *KVClient) error {
  140. // Get all keys with this prefix and delete them
  141. // Note: This is a simplified version - in production you'd want batch delete
  142. values, err := c.Reads(dataPrefix)
  143. if err != nil {
  144. return err
  145. }
  146. // The Reads command returns values, not keys, so we can't delete them directly
  147. // In a real implementation, we'd need a keys scan command
  148. _ = values
  149. return nil
  150. })
  151. // Delete schema
  152. err = m.pool.WithClient(func(c *KVClient) error {
  153. return c.Delete(key)
  154. })
  155. if err != nil {
  156. return fmt.Errorf("failed to delete schema: %w", err)
  157. }
  158. // Update catalog
  159. if err := m.removeFromCatalog(name); err != nil {
  160. return err
  161. }
  162. // Update cache
  163. delete(m.cache, strings.ToLower(name))
  164. return nil
  165. }
  166. // GetSchema retrieves a table schema.
  167. func (m *SchemaManager) GetSchema(name string) (*Schema, error) {
  168. m.mu.RLock()
  169. if schema, ok := m.cache[strings.ToLower(name)]; ok {
  170. m.mu.RUnlock()
  171. return schema, nil
  172. }
  173. m.mu.RUnlock()
  174. m.mu.Lock()
  175. defer m.mu.Unlock()
  176. // Double-check after acquiring write lock
  177. if schema, ok := m.cache[strings.ToLower(name)]; ok {
  178. return schema, nil
  179. }
  180. key := m.schemaKey(name)
  181. var data string
  182. err := m.pool.WithClient(func(c *KVClient) error {
  183. var err error
  184. data, err = c.Read(key)
  185. return err
  186. })
  187. if err != nil {
  188. if err == ErrKeyNotFound {
  189. return nil, fmt.Errorf("table not found: %s", name)
  190. }
  191. return nil, err
  192. }
  193. var schema Schema
  194. if err := json.Unmarshal([]byte(data), &schema); err != nil {
  195. return nil, fmt.Errorf("failed to parse schema: %w", err)
  196. }
  197. m.cache[strings.ToLower(name)] = &schema
  198. return &schema, nil
  199. }
  200. // TableExists checks if a table exists.
  201. func (m *SchemaManager) TableExists(name string) bool {
  202. _, err := m.GetSchema(name)
  203. return err == nil
  204. }
  205. // ListTables returns all table names.
  206. func (m *SchemaManager) ListTables() ([]string, error) {
  207. var data string
  208. err := m.pool.WithClient(func(c *KVClient) error {
  209. var err error
  210. data, err = c.Read(m.catalogKey())
  211. return err
  212. })
  213. if err != nil {
  214. if err == ErrKeyNotFound {
  215. return nil, nil
  216. }
  217. return nil, err
  218. }
  219. var tables []string
  220. if err := json.Unmarshal([]byte(data), &tables); err != nil {
  221. return nil, fmt.Errorf("failed to parse catalog: %w", err)
  222. }
  223. return tables, nil
  224. }
  225. // addToCatalog adds a table to the catalog.
  226. func (m *SchemaManager) addToCatalog(name string) error {
  227. tables, err := m.ListTables()
  228. if err != nil && err != ErrKeyNotFound {
  229. return err
  230. }
  231. // Check if already exists
  232. lowerName := strings.ToLower(name)
  233. for _, t := range tables {
  234. if strings.ToLower(t) == lowerName {
  235. return nil
  236. }
  237. }
  238. tables = append(tables, name)
  239. data, err := json.Marshal(tables)
  240. if err != nil {
  241. return err
  242. }
  243. return m.pool.WithClient(func(c *KVClient) error {
  244. return c.Write(m.catalogKey(), string(data))
  245. })
  246. }
  247. // removeFromCatalog removes a table from the catalog.
  248. func (m *SchemaManager) removeFromCatalog(name string) error {
  249. tables, err := m.ListTables()
  250. if err != nil {
  251. return err
  252. }
  253. lowerName := strings.ToLower(name)
  254. newTables := make([]string, 0, len(tables))
  255. for _, t := range tables {
  256. if strings.ToLower(t) != lowerName {
  257. newTables = append(newTables, t)
  258. }
  259. }
  260. data, err := json.Marshal(newTables)
  261. if err != nil {
  262. return err
  263. }
  264. return m.pool.WithClient(func(c *KVClient) error {
  265. return c.Write(m.catalogKey(), string(data))
  266. })
  267. }
  268. // InvalidateCache clears the cache for a table.
  269. func (m *SchemaManager) InvalidateCache(name string) {
  270. m.mu.Lock()
  271. defer m.mu.Unlock()
  272. delete(m.cache, strings.ToLower(name))
  273. }
  274. // ToAnalyzerTableInfo converts a Schema to analyzer.TableInfo.
  275. func (s *Schema) ToAnalyzerTableInfo() *analyzer.TableInfo {
  276. info := &analyzer.TableInfo{
  277. Name: s.Name,
  278. }
  279. for _, col := range s.Columns {
  280. info.Columns = append(info.Columns, analyzer.ColumnInfo{
  281. Name: col.Name,
  282. Type: analyzer.TypeFromName(col.Type),
  283. Nullable: col.Nullable,
  284. PrimaryKey: col.PrimaryKey,
  285. TableName: s.Name,
  286. })
  287. }
  288. return info
  289. }
  290. // GetColumn returns a column by name.
  291. func (s *Schema) GetColumn(name string) (*Column, bool) {
  292. lowerName := strings.ToLower(name)
  293. for i := range s.Columns {
  294. if strings.ToLower(s.Columns[i].Name) == lowerName {
  295. return &s.Columns[i], true
  296. }
  297. }
  298. return nil, false
  299. }
  300. // GetNextRowID gets and increments the next ROWID for a table.
  301. func (m *SchemaManager) GetNextRowID(table string) (int64, error) {
  302. m.mu.Lock()
  303. defer m.mu.Unlock()
  304. schema, err := m.getSchemaLocked(table)
  305. if err != nil {
  306. return 0, err
  307. }
  308. // Get current and increment
  309. rowid := schema.NextRowID
  310. if rowid == 0 {
  311. rowid = 1
  312. }
  313. schema.NextRowID = rowid + 1
  314. // Save updated schema
  315. if err := m.saveSchemaLocked(schema); err != nil {
  316. return 0, err
  317. }
  318. return rowid, nil
  319. }
  320. // UpdateMaxRowID updates the next ROWID if the provided value is higher.
  321. func (m *SchemaManager) UpdateMaxRowID(table string, rowid int64) error {
  322. m.mu.Lock()
  323. defer m.mu.Unlock()
  324. schema, err := m.getSchemaLocked(table)
  325. if err != nil {
  326. return err
  327. }
  328. if rowid >= schema.NextRowID {
  329. schema.NextRowID = rowid + 1
  330. return m.saveSchemaLocked(schema)
  331. }
  332. return nil
  333. }
  334. // getSchemaLocked retrieves schema (must hold lock).
  335. func (m *SchemaManager) getSchemaLocked(name string) (*Schema, error) {
  336. if schema, ok := m.cache[strings.ToLower(name)]; ok {
  337. return schema, nil
  338. }
  339. key := m.schemaKey(name)
  340. var data string
  341. err := m.pool.WithClient(func(c *KVClient) error {
  342. var err error
  343. data, err = c.Read(key)
  344. return err
  345. })
  346. if err != nil {
  347. if err == ErrKeyNotFound {
  348. return nil, fmt.Errorf("table not found: %s", name)
  349. }
  350. return nil, err
  351. }
  352. var schema Schema
  353. if err := json.Unmarshal([]byte(data), &schema); err != nil {
  354. return nil, fmt.Errorf("failed to parse schema: %w", err)
  355. }
  356. m.cache[strings.ToLower(name)] = &schema
  357. return &schema, nil
  358. }
  359. // saveSchemaLocked saves schema (must hold lock).
  360. func (m *SchemaManager) saveSchemaLocked(schema *Schema) error {
  361. data, err := json.Marshal(schema)
  362. if err != nil {
  363. return fmt.Errorf("failed to serialize schema: %w", err)
  364. }
  365. key := m.schemaKey(schema.Name)
  366. err = m.pool.WithClient(func(c *KVClient) error {
  367. return c.Write(key, string(data))
  368. })
  369. if err != nil {
  370. return fmt.Errorf("failed to write schema: %w", err)
  371. }
  372. m.cache[strings.ToLower(schema.Name)] = schema
  373. return nil
  374. }
  375. // Index management methods
  376. // indexKey returns the key for an index.
  377. func (m *SchemaManager) indexKey(name string) string {
  378. return fmt.Sprintf("%s:index:%s", m.database, strings.ToLower(name))
  379. }
  380. // indexListKey returns the key for the index list.
  381. func (m *SchemaManager) indexListKey() string {
  382. return fmt.Sprintf("%s:indexes", m.database)
  383. }
  384. // CreateIndex creates a new index.
  385. func (m *SchemaManager) CreateIndex(index *Index) error {
  386. m.mu.Lock()
  387. defer m.mu.Unlock()
  388. // Check if index already exists
  389. key := m.indexKey(index.Name)
  390. err := m.pool.WithClient(func(c *KVClient) error {
  391. _, err := c.Read(key)
  392. return err
  393. })
  394. if err == nil {
  395. return fmt.Errorf("index already exists: %s", index.Name)
  396. }
  397. // Verify table exists
  398. if _, err := m.getSchemaLocked(index.Table); err != nil {
  399. return fmt.Errorf("table not found: %s", index.Table)
  400. }
  401. // Save index
  402. index.CreatedAt = time.Now()
  403. data, err := json.Marshal(index)
  404. if err != nil {
  405. return fmt.Errorf("failed to serialize index: %w", err)
  406. }
  407. err = m.pool.WithClient(func(c *KVClient) error {
  408. return c.Write(key, string(data))
  409. })
  410. if err != nil {
  411. return fmt.Errorf("failed to write index: %w", err)
  412. }
  413. // Add to index list
  414. return m.addToIndexList(index.Name)
  415. }
  416. // DropIndex drops an index.
  417. func (m *SchemaManager) DropIndex(name string) error {
  418. m.mu.Lock()
  419. defer m.mu.Unlock()
  420. key := m.indexKey(name)
  421. err := m.pool.WithClient(func(c *KVClient) error {
  422. return c.Delete(key)
  423. })
  424. if err != nil {
  425. return fmt.Errorf("failed to delete index: %w", err)
  426. }
  427. return m.removeFromIndexList(name)
  428. }
  429. // IndexExists checks if an index exists.
  430. func (m *SchemaManager) IndexExists(name string) bool {
  431. m.mu.RLock()
  432. defer m.mu.RUnlock()
  433. key := m.indexKey(name)
  434. err := m.pool.WithClient(func(c *KVClient) error {
  435. _, err := c.Read(key)
  436. return err
  437. })
  438. return err == nil
  439. }
  440. // GetIndex retrieves an index by name.
  441. func (m *SchemaManager) GetIndex(name string) (*Index, error) {
  442. m.mu.RLock()
  443. defer m.mu.RUnlock()
  444. key := m.indexKey(name)
  445. var data string
  446. err := m.pool.WithClient(func(c *KVClient) error {
  447. var err error
  448. data, err = c.Read(key)
  449. return err
  450. })
  451. if err != nil {
  452. return nil, fmt.Errorf("index not found: %s", name)
  453. }
  454. var index Index
  455. if err := json.Unmarshal([]byte(data), &index); err != nil {
  456. return nil, fmt.Errorf("failed to parse index: %w", err)
  457. }
  458. return &index, nil
  459. }
  460. // ListIndexes returns all index names.
  461. func (m *SchemaManager) ListIndexes() ([]string, error) {
  462. m.mu.RLock()
  463. defer m.mu.RUnlock()
  464. key := m.indexListKey()
  465. var data string
  466. err := m.pool.WithClient(func(c *KVClient) error {
  467. var err error
  468. data, err = c.Read(key)
  469. return err
  470. })
  471. if err != nil {
  472. return []string{}, nil
  473. }
  474. var indexes []string
  475. if err := json.Unmarshal([]byte(data), &indexes); err != nil {
  476. return []string{}, nil
  477. }
  478. return indexes, nil
  479. }
  480. // ListTableIndexes returns all indexes for a table.
  481. func (m *SchemaManager) ListTableIndexes(table string) ([]*Index, error) {
  482. indexes, err := m.ListIndexes()
  483. if err != nil {
  484. return nil, err
  485. }
  486. var result []*Index
  487. for _, name := range indexes {
  488. idx, err := m.GetIndex(name)
  489. if err != nil {
  490. continue
  491. }
  492. if strings.EqualFold(idx.Table, table) {
  493. result = append(result, idx)
  494. }
  495. }
  496. return result, nil
  497. }
  498. // addToIndexList adds an index name to the list.
  499. func (m *SchemaManager) addToIndexList(name string) error {
  500. key := m.indexListKey()
  501. var indexes []string
  502. var data string
  503. err := m.pool.WithClient(func(c *KVClient) error {
  504. var err error
  505. data, err = c.Read(key)
  506. return err
  507. })
  508. if err == nil {
  509. json.Unmarshal([]byte(data), &indexes)
  510. }
  511. indexes = append(indexes, name)
  512. newData, _ := json.Marshal(indexes)
  513. return m.pool.WithClient(func(c *KVClient) error {
  514. return c.Write(key, string(newData))
  515. })
  516. }
  517. // removeFromIndexList removes an index name from the list.
  518. func (m *SchemaManager) removeFromIndexList(name string) error {
  519. key := m.indexListKey()
  520. var indexes []string
  521. var data string
  522. err := m.pool.WithClient(func(c *KVClient) error {
  523. var err error
  524. data, err = c.Read(key)
  525. return err
  526. })
  527. if err != nil {
  528. return nil
  529. }
  530. json.Unmarshal([]byte(data), &indexes)
  531. var newIndexes []string
  532. for _, idx := range indexes {
  533. if !strings.EqualFold(idx, name) {
  534. newIndexes = append(newIndexes, idx)
  535. }
  536. }
  537. newData, _ := json.Marshal(newIndexes)
  538. return m.pool.WithClient(func(c *KVClient) error {
  539. return c.Write(key, string(newData))
  540. })
  541. }
  542. // AddColumn adds a new column to a table.
  543. func (m *SchemaManager) AddColumn(table string, column Column) error {
  544. m.mu.Lock()
  545. defer m.mu.Unlock()
  546. schema, err := m.getSchemaUnsafe(table)
  547. if err != nil {
  548. return err
  549. }
  550. // Check if column already exists
  551. for _, col := range schema.Columns {
  552. if strings.EqualFold(col.Name, column.Name) {
  553. return fmt.Errorf("column already exists: %s", column.Name)
  554. }
  555. }
  556. // Add column
  557. schema.Columns = append(schema.Columns, column)
  558. // Update schema
  559. return m.updateSchemaUnsafe(schema)
  560. }
  561. // DropColumn removes a column from a table.
  562. func (m *SchemaManager) DropColumn(table, columnName string) error {
  563. m.mu.Lock()
  564. defer m.mu.Unlock()
  565. schema, err := m.getSchemaUnsafe(table)
  566. if err != nil {
  567. return err
  568. }
  569. // Cannot drop primary key column
  570. if strings.EqualFold(schema.PrimaryKey, columnName) {
  571. return fmt.Errorf("cannot drop primary key column: %s", columnName)
  572. }
  573. // Find and remove column
  574. newColumns := make([]Column, 0, len(schema.Columns)-1)
  575. found := false
  576. for _, col := range schema.Columns {
  577. if strings.EqualFold(col.Name, columnName) {
  578. found = true
  579. continue
  580. }
  581. newColumns = append(newColumns, col)
  582. }
  583. if !found {
  584. return fmt.Errorf("column not found: %s", columnName)
  585. }
  586. schema.Columns = newColumns
  587. // Update schema
  588. return m.updateSchemaUnsafe(schema)
  589. }
  590. // RenameTable renames a table.
  591. func (m *SchemaManager) RenameTable(oldName, newName string) error {
  592. m.mu.Lock()
  593. defer m.mu.Unlock()
  594. // Check if old table exists
  595. schema, err := m.getSchemaUnsafe(oldName)
  596. if err != nil {
  597. return err
  598. }
  599. // Check if new table name already exists
  600. _, err = m.getSchemaUnsafe(newName)
  601. if err == nil {
  602. return fmt.Errorf("table already exists: %s", newName)
  603. }
  604. // Update schema name
  605. schema.Name = newName
  606. // Delete old schema
  607. oldKey := m.schemaKey(oldName)
  608. err = m.pool.WithClient(func(c *KVClient) error {
  609. return c.Delete(oldKey)
  610. })
  611. if err != nil {
  612. return err
  613. }
  614. // Remove from catalog
  615. m.removeFromCatalog(oldName)
  616. // Update cache
  617. delete(m.cache, strings.ToLower(oldName))
  618. // Write new schema
  619. newKey := m.schemaKey(newName)
  620. data, _ := json.Marshal(schema)
  621. err = m.pool.WithClient(func(c *KVClient) error {
  622. return c.Write(newKey, string(data))
  623. })
  624. if err != nil {
  625. return err
  626. }
  627. // Add to catalog
  628. m.addToCatalog(newName)
  629. // Update cache
  630. m.cache[strings.ToLower(newName)] = schema
  631. return nil
  632. }
  633. // RenameColumn renames a column in a table.
  634. func (m *SchemaManager) RenameColumn(table, oldName, newName string) error {
  635. m.mu.Lock()
  636. defer m.mu.Unlock()
  637. schema, err := m.getSchemaUnsafe(table)
  638. if err != nil {
  639. return err
  640. }
  641. // Check if new column name already exists
  642. for _, col := range schema.Columns {
  643. if strings.EqualFold(col.Name, newName) {
  644. return fmt.Errorf("column already exists: %s", newName)
  645. }
  646. }
  647. // Find and rename column
  648. found := false
  649. for i, col := range schema.Columns {
  650. if strings.EqualFold(col.Name, oldName) {
  651. schema.Columns[i].Name = newName
  652. found = true
  653. // Update primary key reference if needed
  654. if strings.EqualFold(schema.PrimaryKey, oldName) {
  655. schema.PrimaryKey = newName
  656. }
  657. break
  658. }
  659. }
  660. if !found {
  661. return fmt.Errorf("column not found: %s", oldName)
  662. }
  663. // Update schema
  664. return m.updateSchemaUnsafe(schema)
  665. }
  666. // getSchemaUnsafe gets a schema without locking (internal use).
  667. func (m *SchemaManager) getSchemaUnsafe(table string) (*Schema, error) {
  668. tableLower := strings.ToLower(table)
  669. // Check cache
  670. if schema, ok := m.cache[tableLower]; ok {
  671. return schema, nil
  672. }
  673. // Read from storage
  674. key := m.schemaKey(table)
  675. var data string
  676. err := m.pool.WithClient(func(c *KVClient) error {
  677. var err error
  678. data, err = c.Read(key)
  679. return err
  680. })
  681. if err != nil {
  682. return nil, fmt.Errorf("table not found: %s", table)
  683. }
  684. var schema Schema
  685. if err := json.Unmarshal([]byte(data), &schema); err != nil {
  686. return nil, err
  687. }
  688. m.cache[tableLower] = &schema
  689. return &schema, nil
  690. }
  691. // updateSchemaUnsafe updates a schema without locking (internal use).
  692. func (m *SchemaManager) updateSchemaUnsafe(schema *Schema) error {
  693. key := m.schemaKey(schema.Name)
  694. data, _ := json.Marshal(schema)
  695. err := m.pool.WithClient(func(c *KVClient) error {
  696. return c.Write(key, string(data))
  697. })
  698. if err != nil {
  699. return err
  700. }
  701. // Update cache
  702. m.cache[strings.ToLower(schema.Name)] = schema
  703. return nil
  704. }