2
0

schema.go 25 KB

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