2
0

schema.go 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384
  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. // GeneratedExpr holds the SQL text of a GENERATED ALWAYS AS (expr) column.
  32. // GeneratedStored reports whether the value is materialized on write
  33. // (STORED, the only form this engine persists) versus computed on read.
  34. GeneratedExpr string `json:"generated_expr,omitempty"`
  35. GeneratedStored bool `json:"generated_stored,omitempty"`
  36. }
  37. // Index represents an index definition.
  38. type Index struct {
  39. Name string `json:"name"`
  40. Table string `json:"table"`
  41. Columns []IndexColumn `json:"columns"`
  42. Unique bool `json:"unique"`
  43. CreatedAt time.Time `json:"created_at"`
  44. // OnConflict is the default conflict resolution declared for this index via
  45. // a UNIQUE(...) ON CONFLICT clause. Empty means the SQLite default (ABORT).
  46. OnConflict string `json:"on_conflict,omitempty"`
  47. }
  48. // IndexColumn represents a column in an index. Expression is set for expression
  49. // indexes (e.g. lower(email)); a plain column index leaves it empty and uses
  50. // Name.
  51. type IndexColumn struct {
  52. Name string `json:"name"`
  53. Desc bool `json:"desc"`
  54. Expression string `json:"expression,omitempty"`
  55. }
  56. // rowIDAllocator owns the next-ROWID state for a single table. It is a separate
  57. // mutex per table so allocating a ROWID on one table never serializes against
  58. // another table, and never contends with the SchemaManager catalog lock.
  59. type rowIDAllocator struct {
  60. mu sync.Mutex
  61. next int64
  62. init bool
  63. }
  64. // SchemaManager manages table schemas.
  65. type SchemaManager struct {
  66. pool *KVPool
  67. database string
  68. cache map[string]*Schema
  69. indexCache map[string]*Index
  70. indexListCache []string
  71. indexListCached bool
  72. version uint64
  73. mu sync.RWMutex
  74. tableLocksMu sync.Mutex
  75. tableLocks map[string]*sync.RWMutex
  76. rowIDMu sync.Mutex
  77. rowIDAlloc map[string]*rowIDAllocator
  78. }
  79. // BeginTransaction is retained for API compatibility. Buffered per-session
  80. // transactions no longer take a database-wide transaction lock; staged writes
  81. // are validated and committed atomically with CompareBatchWrite instead.
  82. func (m *SchemaManager) BeginTransaction() {}
  83. // EndTransaction is retained for API compatibility.
  84. func (m *SchemaManager) EndTransaction() {}
  85. // LockStatement is retained for API compatibility. Statement execution is now
  86. // serialized through per-table locks and optimistic validation, so no global
  87. // statement lock is required.
  88. func (m *SchemaManager) LockStatement() {}
  89. // UnlockStatement is retained for API compatibility.
  90. func (m *SchemaManager) UnlockStatement() {}
  91. // NewSchemaManager creates a new schema manager.
  92. func NewSchemaManager(pool *KVPool, database string) *SchemaManager {
  93. return &SchemaManager{
  94. pool: pool,
  95. database: database,
  96. cache: make(map[string]*Schema),
  97. indexCache: make(map[string]*Index),
  98. tableLocks: make(map[string]*sync.RWMutex),
  99. rowIDAlloc: make(map[string]*rowIDAllocator),
  100. }
  101. }
  102. // rowIDAllocatorFor returns (creating if needed) the per-table ROWID allocator.
  103. func (m *SchemaManager) rowIDAllocatorFor(table string) *rowIDAllocator {
  104. key := strings.ToLower(table)
  105. m.rowIDMu.Lock()
  106. a, ok := m.rowIDAlloc[key]
  107. if !ok {
  108. a = &rowIDAllocator{}
  109. m.rowIDAlloc[key] = a
  110. }
  111. m.rowIDMu.Unlock()
  112. return a
  113. }
  114. func (m *SchemaManager) tableLock(table string) *sync.RWMutex {
  115. key := strings.ToLower(table)
  116. m.tableLocksMu.Lock()
  117. lock, ok := m.tableLocks[key]
  118. if !ok {
  119. lock = &sync.RWMutex{}
  120. m.tableLocks[key] = lock
  121. }
  122. m.tableLocksMu.Unlock()
  123. return lock
  124. }
  125. // GetDatabaseName returns the database name.
  126. func (m *SchemaManager) GetDatabaseName() string {
  127. return m.database
  128. }
  129. // GetPool returns the KV pool.
  130. func (m *SchemaManager) GetPool() *KVPool {
  131. return m.pool
  132. }
  133. // Version returns the in-process schema catalog version. It is incremented for
  134. // schema/index definition changes so cached executors can resync their analyzer
  135. // catalogs without scanning storage on every query.
  136. func (m *SchemaManager) Version() uint64 {
  137. m.mu.RLock()
  138. defer m.mu.RUnlock()
  139. return m.version
  140. }
  141. func (m *SchemaManager) bumpVersionLocked() {
  142. m.version++
  143. }
  144. // schemaKey returns the key for a table schema.
  145. func (m *SchemaManager) schemaKey(table string) string {
  146. return fmt.Sprintf("%s:_schema:%s", m.database, strings.ToLower(table))
  147. }
  148. // catalogKey returns the key for the table catalog.
  149. func (m *SchemaManager) catalogKey() string {
  150. return fmt.Sprintf("%s:_sys:tables", m.database)
  151. }
  152. // rowIDKey returns the key for a table's next ROWID counter.
  153. func (m *SchemaManager) rowIDKey(table string) string {
  154. return fmt.Sprintf("%s:_sys:rowid:%s", m.database, strings.ToLower(table))
  155. }
  156. // CreateTable creates a new table.
  157. func (m *SchemaManager) CreateTable(schema *Schema) error {
  158. m.mu.Lock()
  159. defer m.mu.Unlock()
  160. // Check if table already exists
  161. key := m.schemaKey(schema.Name)
  162. err := m.pool.WithClient(func(c *KVClient) error {
  163. _, err := c.Read(key)
  164. return err
  165. })
  166. if err == nil {
  167. return fmt.Errorf("table already exists: %s", schema.Name)
  168. }
  169. // Keep the cached schema private so callers cannot mutate a published
  170. // catalog snapshot after this operation returns.
  171. schema = cloneSchema(schema)
  172. schema.CreatedAt = time.Now()
  173. // Determine primary key if not set
  174. if schema.PrimaryKey == "" {
  175. for _, col := range schema.Columns {
  176. if col.PrimaryKey {
  177. schema.PrimaryKey = col.Name
  178. break
  179. }
  180. }
  181. // No explicit primary key declared — use synthetic _rowid_ so user
  182. // columns remain unconstrained and can hold duplicate or NULL values.
  183. if schema.PrimaryKey == "" {
  184. schema.PrimaryKey = "_rowid_"
  185. }
  186. }
  187. // Serialize schema
  188. data, err := json.Marshal(schema)
  189. if err != nil {
  190. return fmt.Errorf("failed to serialize schema: %w", err)
  191. }
  192. // Write schema
  193. err = m.pool.WithClient(func(c *KVClient) error {
  194. return c.Write(key, string(data))
  195. })
  196. if err != nil {
  197. return fmt.Errorf("failed to write schema: %w", err)
  198. }
  199. // Update catalog
  200. if err := m.addToCatalog(schema.Name); err != nil {
  201. // Rollback schema write
  202. m.pool.WithClient(func(c *KVClient) error {
  203. return c.Delete(key)
  204. })
  205. return err
  206. }
  207. // Update cache
  208. m.cache[strings.ToLower(schema.Name)] = schema
  209. m.bumpVersionLocked()
  210. return nil
  211. }
  212. // DropTable drops a table.
  213. func (m *SchemaManager) DropTable(name string) error {
  214. tableLock := m.tableLock(name)
  215. tableLock.Lock()
  216. defer tableLock.Unlock()
  217. m.mu.Lock()
  218. defer m.mu.Unlock()
  219. key := m.schemaKey(name)
  220. // Check if table exists
  221. err := m.pool.WithClient(func(c *KVClient) error {
  222. _, err := c.Read(key)
  223. return err
  224. })
  225. if err != nil {
  226. return fmt.Errorf("table not found: %s", name)
  227. }
  228. // Delete all rows by scanning their actual keys and batch-deleting them, so
  229. // a table drop no longer leaks durable rows.
  230. if err := m.deleteKeysWithPrefix([]byte(fmt.Sprintf("%s:_data:%s:", m.database, strings.ToLower(name)))); err != nil {
  231. return err
  232. }
  233. // Delete schema
  234. err = m.pool.WithClient(func(c *KVClient) error {
  235. return c.Delete(key)
  236. })
  237. if err != nil {
  238. return fmt.Errorf("failed to delete schema: %w", err)
  239. }
  240. // Delete ROWID state.
  241. m.pool.WithClient(func(c *KVClient) error {
  242. return c.Delete(m.rowIDKey(name))
  243. })
  244. // Update catalog
  245. if err := m.removeFromCatalog(name); err != nil {
  246. return err
  247. }
  248. // Update cache
  249. tableLower := strings.ToLower(name)
  250. delete(m.cache, tableLower)
  251. m.rowIDMu.Lock()
  252. delete(m.rowIDAlloc, tableLower)
  253. m.rowIDMu.Unlock()
  254. m.bumpVersionLocked()
  255. return nil
  256. }
  257. // GetSchema retrieves a table schema.
  258. func (m *SchemaManager) GetSchema(name string) (*Schema, error) {
  259. m.mu.RLock()
  260. if schema, ok := m.cache[strings.ToLower(name)]; ok {
  261. // Clone while still holding the read lock: the cached schema's
  262. // NextRowID field is mutated under the write lock, so cloning outside
  263. // the lock races with that mutation.
  264. cloned := cloneSchema(schema)
  265. m.mu.RUnlock()
  266. return cloned, nil
  267. }
  268. m.mu.RUnlock()
  269. m.mu.Lock()
  270. defer m.mu.Unlock()
  271. // Double-check after acquiring write lock
  272. if schema, ok := m.cache[strings.ToLower(name)]; ok {
  273. return cloneSchema(schema), nil
  274. }
  275. key := m.schemaKey(name)
  276. var data string
  277. err := m.pool.WithClient(func(c *KVClient) error {
  278. var err error
  279. data, err = c.Read(key)
  280. return err
  281. })
  282. if err != nil {
  283. if err == ErrKeyNotFound {
  284. return nil, fmt.Errorf("table not found: %s", name)
  285. }
  286. return nil, err
  287. }
  288. var schema Schema
  289. if err := json.Unmarshal([]byte(data), &schema); err != nil {
  290. return nil, fmt.Errorf("failed to parse schema: %w", err)
  291. }
  292. m.cache[strings.ToLower(name)] = &schema
  293. return cloneSchema(&schema), nil
  294. }
  295. func cloneSchema(schema *Schema) *Schema {
  296. if schema == nil {
  297. return nil
  298. }
  299. cloned := *schema
  300. cloned.Columns = append([]Column(nil), schema.Columns...)
  301. return &cloned
  302. }
  303. func cloneIndex(index *Index) *Index {
  304. if index == nil {
  305. return nil
  306. }
  307. cloned := *index
  308. cloned.Columns = append([]IndexColumn(nil), index.Columns...)
  309. return &cloned
  310. }
  311. // TableExists checks if a table exists.
  312. func (m *SchemaManager) TableExists(name string) bool {
  313. _, err := m.GetSchema(name)
  314. return err == nil
  315. }
  316. // ListTables returns all table names.
  317. func (m *SchemaManager) ListTables() ([]string, error) {
  318. var data string
  319. err := m.pool.WithClient(func(c *KVClient) error {
  320. var err error
  321. data, err = c.Read(m.catalogKey())
  322. return err
  323. })
  324. if err != nil {
  325. if err == ErrKeyNotFound {
  326. return nil, nil
  327. }
  328. return nil, err
  329. }
  330. var tables []string
  331. if err := json.Unmarshal([]byte(data), &tables); err != nil {
  332. return nil, fmt.Errorf("failed to parse catalog: %w", err)
  333. }
  334. return tables, nil
  335. }
  336. // addToCatalog adds a table to the catalog.
  337. func (m *SchemaManager) addToCatalog(name string) error {
  338. tables, err := m.ListTables()
  339. if err != nil && err != ErrKeyNotFound {
  340. return err
  341. }
  342. // Check if already exists
  343. lowerName := strings.ToLower(name)
  344. for _, t := range tables {
  345. if strings.ToLower(t) == lowerName {
  346. return nil
  347. }
  348. }
  349. tables = append(tables, name)
  350. data, err := json.Marshal(tables)
  351. if err != nil {
  352. return err
  353. }
  354. return m.pool.WithClient(func(c *KVClient) error {
  355. return c.Write(m.catalogKey(), string(data))
  356. })
  357. }
  358. // removeFromCatalog removes a table from the catalog.
  359. func (m *SchemaManager) removeFromCatalog(name string) error {
  360. tables, err := m.ListTables()
  361. if err != nil {
  362. return err
  363. }
  364. lowerName := strings.ToLower(name)
  365. newTables := make([]string, 0, len(tables))
  366. for _, t := range tables {
  367. if strings.ToLower(t) != lowerName {
  368. newTables = append(newTables, t)
  369. }
  370. }
  371. data, err := json.Marshal(newTables)
  372. if err != nil {
  373. return err
  374. }
  375. return m.pool.WithClient(func(c *KVClient) error {
  376. return c.Write(m.catalogKey(), string(data))
  377. })
  378. }
  379. // InvalidateCache clears the cache for a table.
  380. func (m *SchemaManager) InvalidateCache(name string) {
  381. m.mu.Lock()
  382. defer m.mu.Unlock()
  383. tableLower := strings.ToLower(name)
  384. delete(m.cache, tableLower)
  385. m.rowIDMu.Lock()
  386. delete(m.rowIDAlloc, tableLower)
  387. m.rowIDMu.Unlock()
  388. }
  389. // ToAnalyzerTableInfo converts a Schema to analyzer.TableInfo.
  390. func (s *Schema) ToAnalyzerTableInfo() *analyzer.TableInfo {
  391. info := &analyzer.TableInfo{
  392. Name: s.Name,
  393. }
  394. for _, col := range s.Columns {
  395. info.Columns = append(info.Columns, analyzer.ColumnInfo{
  396. Name: col.Name,
  397. Type: analyzer.TypeFromName(col.Type),
  398. Nullable: col.Nullable,
  399. PrimaryKey: col.PrimaryKey,
  400. TableName: s.Name,
  401. Generated: col.GeneratedExpr != "",
  402. })
  403. }
  404. return info
  405. }
  406. // GetColumn returns a column by name.
  407. func (s *Schema) GetColumn(name string) (*Column, bool) {
  408. lowerName := strings.ToLower(name)
  409. for i := range s.Columns {
  410. if strings.ToLower(s.Columns[i].Name) == lowerName {
  411. return &s.Columns[i], true
  412. }
  413. }
  414. return nil, false
  415. }
  416. // GetNextRowID gets and increments the next ROWID for a table. Allocation is
  417. // serialized per table via the table's own allocator so inserts on different
  418. // tables never contend, and no global SchemaManager lock is held across the
  419. // durable derivation scan.
  420. func (m *SchemaManager) GetNextRowID(table string) (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 0, err
  427. }
  428. alloc.next = next + 1
  429. return next, nil
  430. }
  431. // UpdateMaxRowID updates the next ROWID if the provided value is higher.
  432. func (m *SchemaManager) UpdateMaxRowID(table string, rowid int64) error {
  433. alloc := m.rowIDAllocatorFor(table)
  434. alloc.mu.Lock()
  435. defer alloc.mu.Unlock()
  436. next, err := m.nextRowIDLocked(alloc, table)
  437. if err != nil {
  438. return err
  439. }
  440. if rowid >= next {
  441. alloc.next = rowid + 1
  442. }
  443. return nil
  444. }
  445. // nextRowIDLocked returns the current next ROWID, deriving it from durable rows
  446. // on first use (must hold the per-table allocator lock).
  447. func (m *SchemaManager) nextRowIDLocked(alloc *rowIDAllocator, table string) (int64, error) {
  448. if alloc.init {
  449. return alloc.next, nil
  450. }
  451. next, err := m.deriveNextRowID(table)
  452. if err != nil {
  453. return 0, err
  454. }
  455. if next < 1 {
  456. next = 1
  457. }
  458. alloc.next = next
  459. alloc.init = true
  460. return alloc.next, nil
  461. }
  462. // deriveNextRowID scans durable row keys to recover max(rowid)+1, streaming
  463. // each page through decodeRow instead of materializing every value.
  464. func (m *SchemaManager) deriveNextRowID(table string) (int64, error) {
  465. prefix := []byte(fmt.Sprintf("%s:_data:%s:", m.database, strings.ToLower(table)))
  466. var maxRowID int64
  467. err := m.pool.WithClient(func(client *KVClient) (retErr error) {
  468. cursor, err := client.Scan(prefix)
  469. if err != nil {
  470. return err
  471. }
  472. defer func() {
  473. if err := cursor.Close(); retErr == nil {
  474. retErr = err
  475. }
  476. }()
  477. for {
  478. entries, done, err := cursor.Next()
  479. if err != nil {
  480. return err
  481. }
  482. for _, e := range entries {
  483. row, err := decodeRow(e.Value)
  484. if err != nil {
  485. return fmt.Errorf("failed to parse row while deriving ROWID: %w", err)
  486. }
  487. if rowid, ok := valueAsInt64(row["_rowid_"]); ok && rowid > maxRowID {
  488. maxRowID = rowid
  489. }
  490. }
  491. if done {
  492. return nil
  493. }
  494. }
  495. })
  496. if err != nil {
  497. return 0, err
  498. }
  499. return maxRowID + 1, nil
  500. }
  501. // deleteKeysWithPrefix streams the keys with the given prefix one page at a
  502. // time and atomically batch-deletes them, so a bulk operation never leaves
  503. // durable rows behind.
  504. func (m *SchemaManager) deleteKeysWithPrefix(prefix []byte) error {
  505. return m.pool.WithClient(func(client *KVClient) (retErr error) {
  506. cursor, err := client.ScanKeys(prefix)
  507. if err != nil {
  508. return err
  509. }
  510. defer func() {
  511. if err := cursor.Close(); retErr == nil {
  512. retErr = err
  513. }
  514. }()
  515. ops := make([]BatchOp, 0, scanPageSize)
  516. batchBytes := 8
  517. flush := func() error {
  518. if len(ops) == 0 {
  519. return nil
  520. }
  521. if _, err := client.BatchWrite(ops, nil); err != nil {
  522. return err
  523. }
  524. ops = ops[:0]
  525. batchBytes = 8
  526. return nil
  527. }
  528. for {
  529. entries, done, err := cursor.Next()
  530. if err != nil {
  531. return err
  532. }
  533. for _, e := range entries {
  534. opBytes := 12 + len(e.Key)
  535. if len(ops) == maxOperations || batchBytes+opBytes > bulkBatchByteBudget {
  536. if err := flush(); err != nil {
  537. return err
  538. }
  539. }
  540. ops = append(ops, BatchOp{Op: batchDelete, Key: append([]byte(nil), e.Key...)})
  541. batchBytes += opBytes
  542. }
  543. if done {
  544. return flush()
  545. }
  546. }
  547. })
  548. }
  549. func valueAsInt64(value interface{}) (int64, bool) {
  550. switch v := value.(type) {
  551. case int64:
  552. return v, true
  553. case int:
  554. return int64(v), true
  555. case float64:
  556. return int64(v), true
  557. default:
  558. return 0, false
  559. }
  560. }
  561. // getSchemaLocked retrieves schema (must hold lock).
  562. func (m *SchemaManager) getSchemaLocked(name string) (*Schema, error) {
  563. if schema, ok := m.cache[strings.ToLower(name)]; ok {
  564. return schema, nil
  565. }
  566. key := m.schemaKey(name)
  567. var data string
  568. err := m.pool.WithClient(func(c *KVClient) error {
  569. var err error
  570. data, err = c.Read(key)
  571. return err
  572. })
  573. if err != nil {
  574. if err == ErrKeyNotFound {
  575. return nil, fmt.Errorf("table not found: %s", name)
  576. }
  577. return nil, err
  578. }
  579. var schema Schema
  580. if err := json.Unmarshal([]byte(data), &schema); err != nil {
  581. return nil, fmt.Errorf("failed to parse schema: %w", err)
  582. }
  583. m.cache[strings.ToLower(name)] = &schema
  584. return &schema, nil
  585. }
  586. // saveSchemaLocked saves schema (must hold lock).
  587. func (m *SchemaManager) saveSchemaLocked(schema *Schema) error {
  588. data, err := json.Marshal(schema)
  589. if err != nil {
  590. return fmt.Errorf("failed to serialize schema: %w", err)
  591. }
  592. key := m.schemaKey(schema.Name)
  593. err = m.pool.WithClient(func(c *KVClient) error {
  594. return c.Write(key, string(data))
  595. })
  596. if err != nil {
  597. return fmt.Errorf("failed to write schema: %w", err)
  598. }
  599. m.cache[strings.ToLower(schema.Name)] = schema
  600. return nil
  601. }
  602. // Index management methods
  603. // indexKey returns the key for an index.
  604. func (m *SchemaManager) indexKey(name string) string {
  605. return fmt.Sprintf("%s:index:%s", m.database, strings.ToLower(name))
  606. }
  607. // indexListKey returns the key for the index list.
  608. func (m *SchemaManager) indexListKey() string {
  609. return fmt.Sprintf("%s:indexes", m.database)
  610. }
  611. // CreateIndex creates a new index.
  612. func (m *SchemaManager) CreateIndex(index *Index) error {
  613. m.mu.Lock()
  614. defer m.mu.Unlock()
  615. // Check if index already exists
  616. key := m.indexKey(index.Name)
  617. err := m.pool.WithClient(func(c *KVClient) error {
  618. _, err := c.Read(key)
  619. return err
  620. })
  621. if err == nil {
  622. return fmt.Errorf("index already exists: %s", index.Name)
  623. }
  624. // Verify table exists
  625. if _, err := m.getSchemaLocked(index.Table); err != nil {
  626. return fmt.Errorf("table not found: %s", index.Table)
  627. }
  628. // Save index
  629. index.CreatedAt = time.Now()
  630. data, err := json.Marshal(index)
  631. if err != nil {
  632. return fmt.Errorf("failed to serialize index: %w", err)
  633. }
  634. err = m.pool.WithClient(func(c *KVClient) error {
  635. return c.Write(key, string(data))
  636. })
  637. if err != nil {
  638. return fmt.Errorf("failed to write index: %w", err)
  639. }
  640. // Add to index list
  641. if err := m.addToIndexList(index.Name); err != nil {
  642. return err
  643. }
  644. m.indexCache[strings.ToLower(index.Name)] = cloneIndex(index)
  645. m.bumpVersionLocked()
  646. return nil
  647. }
  648. // DropIndex drops an index.
  649. func (m *SchemaManager) DropIndex(name string) error {
  650. m.mu.Lock()
  651. defer m.mu.Unlock()
  652. key := m.indexKey(name)
  653. err := m.pool.WithClient(func(c *KVClient) error {
  654. return c.Delete(key)
  655. })
  656. if err != nil {
  657. return fmt.Errorf("failed to delete index: %w", err)
  658. }
  659. if err := m.removeFromIndexList(name); err != nil {
  660. return err
  661. }
  662. delete(m.indexCache, strings.ToLower(name))
  663. m.bumpVersionLocked()
  664. return nil
  665. }
  666. // IndexExists checks if an index exists.
  667. func (m *SchemaManager) IndexExists(name string) bool {
  668. m.mu.RLock()
  669. defer m.mu.RUnlock()
  670. if _, ok := m.indexCache[strings.ToLower(name)]; ok {
  671. return true
  672. }
  673. key := m.indexKey(name)
  674. err := m.pool.WithClient(func(c *KVClient) error {
  675. _, err := c.Read(key)
  676. return err
  677. })
  678. return err == nil
  679. }
  680. // GetIndex retrieves an index by name.
  681. func (m *SchemaManager) GetIndex(name string) (*Index, error) {
  682. m.mu.Lock()
  683. defer m.mu.Unlock()
  684. cacheKey := strings.ToLower(name)
  685. if index, ok := m.indexCache[cacheKey]; ok {
  686. return cloneIndex(index), nil
  687. }
  688. key := m.indexKey(name)
  689. var data string
  690. err := m.pool.WithClient(func(c *KVClient) error {
  691. var err error
  692. data, err = c.Read(key)
  693. return err
  694. })
  695. if err != nil {
  696. if err == ErrKeyNotFound {
  697. return nil, fmt.Errorf("%w: %s", ErrIndexNotFound, name)
  698. }
  699. return nil, err
  700. }
  701. var index Index
  702. if err := json.Unmarshal([]byte(data), &index); err != nil {
  703. return nil, fmt.Errorf("failed to parse index: %w", err)
  704. }
  705. m.indexCache[cacheKey] = &index
  706. return cloneIndex(&index), nil
  707. }
  708. // ListIndexes returns all index names.
  709. func (m *SchemaManager) ListIndexes() ([]string, error) {
  710. m.mu.Lock()
  711. defer m.mu.Unlock()
  712. if m.indexListCached {
  713. return append([]string(nil), m.indexListCache...), nil
  714. }
  715. key := m.indexListKey()
  716. var data string
  717. err := m.pool.WithClient(func(c *KVClient) error {
  718. var err error
  719. data, err = c.Read(key)
  720. return err
  721. })
  722. if err == ErrKeyNotFound {
  723. m.indexListCache = nil
  724. m.indexListCached = true
  725. return []string{}, nil
  726. }
  727. if err != nil {
  728. return nil, err
  729. }
  730. var indexes []string
  731. if err := json.Unmarshal([]byte(data), &indexes); err != nil {
  732. return nil, fmt.Errorf("failed to parse index list: %w", err)
  733. }
  734. m.indexListCache = append([]string(nil), indexes...)
  735. m.indexListCached = true
  736. return indexes, nil
  737. }
  738. // ListTableIndexes returns all indexes for a table.
  739. func (m *SchemaManager) ListTableIndexes(table string) ([]*Index, error) {
  740. indexes, err := m.ListIndexes()
  741. if err != nil {
  742. return nil, err
  743. }
  744. var result []*Index
  745. for _, name := range indexes {
  746. idx, err := m.GetIndex(name)
  747. if err != nil {
  748. // An index dropped concurrently is simply absent; any other error
  749. // (storage/IO or corrupt data) must not be silently swallowed.
  750. if errors.Is(err, ErrIndexNotFound) {
  751. continue
  752. }
  753. return nil, err
  754. }
  755. if strings.EqualFold(idx.Table, table) {
  756. result = append(result, idx)
  757. }
  758. }
  759. return result, nil
  760. }
  761. // addToIndexList adds an index name to the list.
  762. func (m *SchemaManager) addToIndexList(name string) error {
  763. key := m.indexListKey()
  764. var indexes []string
  765. var data string
  766. err := m.pool.WithClient(func(c *KVClient) error {
  767. var err error
  768. data, err = c.Read(key)
  769. return err
  770. })
  771. if err == nil {
  772. json.Unmarshal([]byte(data), &indexes)
  773. }
  774. indexes = append(indexes, name)
  775. newData, _ := json.Marshal(indexes)
  776. err = m.pool.WithClient(func(c *KVClient) error {
  777. return c.Write(key, string(newData))
  778. })
  779. if err == nil {
  780. m.indexListCache = append([]string(nil), indexes...)
  781. m.indexListCached = true
  782. }
  783. return err
  784. }
  785. // removeFromIndexList removes an index name from the list.
  786. func (m *SchemaManager) removeFromIndexList(name string) error {
  787. key := m.indexListKey()
  788. var indexes []string
  789. var data string
  790. err := m.pool.WithClient(func(c *KVClient) error {
  791. var err error
  792. data, err = c.Read(key)
  793. return err
  794. })
  795. if err != nil {
  796. return nil
  797. }
  798. json.Unmarshal([]byte(data), &indexes)
  799. var newIndexes []string
  800. for _, idx := range indexes {
  801. if !strings.EqualFold(idx, name) {
  802. newIndexes = append(newIndexes, idx)
  803. }
  804. }
  805. newData, _ := json.Marshal(newIndexes)
  806. err = m.pool.WithClient(func(c *KVClient) error {
  807. return c.Write(key, string(newData))
  808. })
  809. if err == nil {
  810. m.indexListCache = append([]string(nil), newIndexes...)
  811. m.indexListCached = true
  812. }
  813. return err
  814. }
  815. // AddColumn adds a new column to a table.
  816. func (m *SchemaManager) AddColumn(table string, column Column) error {
  817. m.mu.Lock()
  818. defer m.mu.Unlock()
  819. schema, err := m.getSchemaUnsafe(table)
  820. if err != nil {
  821. return err
  822. }
  823. // Check if column already exists
  824. for _, col := range schema.Columns {
  825. if strings.EqualFold(col.Name, column.Name) {
  826. return fmt.Errorf("column already exists: %s", column.Name)
  827. }
  828. }
  829. // Publish a fresh snapshot instead of mutating readers' shared pointer.
  830. schema = cloneSchema(schema)
  831. schema.Columns = append(schema.Columns, column)
  832. // Update schema
  833. return m.updateSchemaUnsafe(schema)
  834. }
  835. // DropColumn removes a column from a table.
  836. func (m *SchemaManager) DropColumn(table, columnName string) error {
  837. tableLock := m.tableLock(table)
  838. tableLock.Lock()
  839. defer tableLock.Unlock()
  840. m.mu.Lock()
  841. defer m.mu.Unlock()
  842. schema, err := m.getSchemaUnsafe(table)
  843. if err != nil {
  844. return err
  845. }
  846. // Cannot drop primary key column
  847. if strings.EqualFold(schema.PrimaryKey, columnName) {
  848. return fmt.Errorf("cannot drop primary key column: %s", columnName)
  849. }
  850. // Find and remove column
  851. newColumns := make([]Column, 0, len(schema.Columns)-1)
  852. found := false
  853. for _, col := range schema.Columns {
  854. if strings.EqualFold(col.Name, columnName) {
  855. found = true
  856. continue
  857. }
  858. newColumns = append(newColumns, col)
  859. }
  860. if !found {
  861. return fmt.Errorf("column not found: %s", columnName)
  862. }
  863. schema = cloneSchema(schema)
  864. schema.Columns = newColumns
  865. if err := m.rewriteRows(table, func(row Row) bool {
  866. for key := range row {
  867. if strings.EqualFold(key, columnName) {
  868. delete(row, key)
  869. return true
  870. }
  871. }
  872. return false
  873. }); err != nil {
  874. return err
  875. }
  876. // Update schema
  877. return m.updateSchemaUnsafe(schema)
  878. }
  879. // RenameTable renames a table.
  880. func (m *SchemaManager) RenameTable(oldName, newName string) error {
  881. m.mu.Lock()
  882. defer m.mu.Unlock()
  883. // Check if old table exists
  884. schema, err := m.getSchemaUnsafe(oldName)
  885. if err != nil {
  886. return err
  887. }
  888. // Check if new table name already exists
  889. _, err = m.getSchemaUnsafe(newName)
  890. if err == nil {
  891. return fmt.Errorf("table already exists: %s", newName)
  892. }
  893. schema = cloneSchema(schema)
  894. // Update schema name
  895. schema.Name = newName
  896. // Move durable rows from the old table's data prefix to the new one. Without
  897. // this, ALTER TABLE ... RENAME leaves every row under the old key and the
  898. // renamed table appears empty.
  899. if err := m.renameDataKeys(oldName, newName); err != nil {
  900. return err
  901. }
  902. // Repoint indexes that belonged to the old table.
  903. if err := m.repointIndexesLocked(oldName, newName); err != nil {
  904. return err
  905. }
  906. // Build the replacement catalog before switching schema names. The schema,
  907. // catalog, and stale ROWID state change in one batch, so a crash cannot
  908. // leave neither table name addressable after all row chunks have moved.
  909. tables, err := m.ListTables()
  910. if err != nil {
  911. return err
  912. }
  913. foundOld := false
  914. for i, name := range tables {
  915. if strings.EqualFold(name, oldName) {
  916. tables[i] = newName
  917. foundOld = true
  918. break
  919. }
  920. }
  921. if !foundOld {
  922. return fmt.Errorf("table not found in catalog: %s", oldName)
  923. }
  924. catalogData, err := json.Marshal(tables)
  925. if err != nil {
  926. return err
  927. }
  928. schemaData, err := json.Marshal(schema)
  929. if err != nil {
  930. return err
  931. }
  932. oldKey := m.schemaKey(oldName)
  933. newKey := m.schemaKey(newName)
  934. err = m.pool.WithClient(func(c *KVClient) error {
  935. _, err := c.BatchWrite([]BatchOp{
  936. {Op: batchPut, Key: []byte(newKey), Value: schemaData},
  937. {Op: batchDelete, Key: []byte(oldKey)},
  938. {Op: batchDelete, Key: []byte(m.rowIDKey(oldName))},
  939. {Op: batchPut, Key: []byte(m.catalogKey()), Value: catalogData},
  940. }, nil)
  941. return err
  942. })
  943. if err != nil {
  944. return err
  945. }
  946. // Update cache
  947. oldLower := strings.ToLower(oldName)
  948. newLower := strings.ToLower(newName)
  949. delete(m.cache, oldLower)
  950. m.rowIDMu.Lock()
  951. delete(m.rowIDAlloc, oldLower)
  952. m.rowIDMu.Unlock()
  953. // Update cache
  954. m.cache[newLower] = schema
  955. m.bumpVersionLocked()
  956. return nil
  957. }
  958. // renameDataKeys moves every durable row of a table from the old name's data
  959. // prefix to the new name's prefix in a single atomic batch per page.
  960. func (m *SchemaManager) renameDataKeys(oldName, newName string) error {
  961. oldPrefix := []byte(fmt.Sprintf("%s:_data:%s:", m.database, strings.ToLower(oldName)))
  962. newPrefix := fmt.Sprintf("%s:_data:%s:", m.database, strings.ToLower(newName))
  963. return m.pool.WithClient(func(client *KVClient) (retErr error) {
  964. cursor, err := client.Scan(oldPrefix)
  965. if err != nil {
  966. return err
  967. }
  968. defer func() {
  969. if cerr := cursor.Close(); retErr == nil {
  970. retErr = cerr
  971. }
  972. }()
  973. ops := make([]BatchOp, 0, scanPageSize*2)
  974. batchBytes := 8
  975. flush := func() error {
  976. if len(ops) == 0 {
  977. return nil
  978. }
  979. if _, err := client.BatchWrite(ops, nil); err != nil {
  980. return err
  981. }
  982. ops = ops[:0]
  983. batchBytes = 8
  984. return nil
  985. }
  986. for {
  987. entries, done, err := cursor.Next()
  988. if err != nil {
  989. return err
  990. }
  991. for _, e := range entries {
  992. suffix := string(e.Key[len(oldPrefix):])
  993. newKey := []byte(newPrefix + suffix)
  994. opBytes := 24 + len(newKey) + len(e.Value) + len(e.Key)
  995. if len(ops)+2 > maxOperations || batchBytes+opBytes > bulkBatchByteBudget {
  996. if err := flush(); err != nil {
  997. return err
  998. }
  999. }
  1000. ops = append(ops,
  1001. BatchOp{Op: batchPut, Key: newKey, Value: e.Value},
  1002. BatchOp{Op: batchDelete, Key: append([]byte(nil), e.Key...)},
  1003. )
  1004. batchBytes += opBytes
  1005. }
  1006. if done {
  1007. return flush()
  1008. }
  1009. }
  1010. })
  1011. }
  1012. // repointIndexesLocked updates indexes whose table was renamed. The caller holds
  1013. // m.mu; it reads the durable index list directly rather than calling the
  1014. // self-locking ListIndexes helper.
  1015. func (m *SchemaManager) repointIndexesLocked(oldName, newName string) error {
  1016. var names []string
  1017. if m.indexListCached {
  1018. names = append([]string(nil), m.indexListCache...)
  1019. } else {
  1020. var data string
  1021. err := m.pool.WithClient(func(c *KVClient) error {
  1022. var rerr error
  1023. data, rerr = c.Read(m.indexListKey())
  1024. return rerr
  1025. })
  1026. if err == ErrKeyNotFound {
  1027. return nil
  1028. }
  1029. if err != nil {
  1030. return err
  1031. }
  1032. if err := json.Unmarshal([]byte(data), &names); err != nil {
  1033. return err
  1034. }
  1035. }
  1036. for _, name := range names {
  1037. key := m.indexKey(name)
  1038. var data string
  1039. err := m.pool.WithClient(func(c *KVClient) error {
  1040. var rerr error
  1041. data, rerr = c.Read(key)
  1042. return rerr
  1043. })
  1044. if err != nil {
  1045. if err == ErrKeyNotFound {
  1046. continue
  1047. }
  1048. return err
  1049. }
  1050. var idx Index
  1051. if err := json.Unmarshal([]byte(data), &idx); err != nil {
  1052. return err
  1053. }
  1054. if !strings.EqualFold(idx.Table, oldName) {
  1055. continue
  1056. }
  1057. idx.Table = newName
  1058. updated, err := json.Marshal(&idx)
  1059. if err != nil {
  1060. return err
  1061. }
  1062. if err := m.pool.WithClient(func(c *KVClient) error {
  1063. return c.Write(key, string(updated))
  1064. }); err != nil {
  1065. return err
  1066. }
  1067. if cached, ok := m.indexCache[strings.ToLower(name)]; ok {
  1068. cached.Table = newName
  1069. }
  1070. }
  1071. return nil
  1072. }
  1073. // RenameColumn renames a column in a table.
  1074. func (m *SchemaManager) RenameColumn(table, oldName, newName string) error {
  1075. tableLock := m.tableLock(table)
  1076. tableLock.Lock()
  1077. defer tableLock.Unlock()
  1078. m.mu.Lock()
  1079. defer m.mu.Unlock()
  1080. schema, err := m.getSchemaUnsafe(table)
  1081. if err != nil {
  1082. return err
  1083. }
  1084. // Check if new column name already exists
  1085. for _, col := range schema.Columns {
  1086. if strings.EqualFold(col.Name, newName) {
  1087. return fmt.Errorf("column already exists: %s", newName)
  1088. }
  1089. }
  1090. schema = cloneSchema(schema)
  1091. // Find and rename column
  1092. found := false
  1093. for i, col := range schema.Columns {
  1094. if strings.EqualFold(col.Name, oldName) {
  1095. schema.Columns[i].Name = newName
  1096. found = true
  1097. // Update primary key reference if needed
  1098. if strings.EqualFold(schema.PrimaryKey, oldName) {
  1099. schema.PrimaryKey = newName
  1100. }
  1101. break
  1102. }
  1103. }
  1104. if !found {
  1105. return fmt.Errorf("column not found: %s", oldName)
  1106. }
  1107. if err := m.rewriteRows(table, func(row Row) bool {
  1108. for key, value := range row {
  1109. if strings.EqualFold(key, oldName) {
  1110. delete(row, key)
  1111. row[newName] = value
  1112. return true
  1113. }
  1114. }
  1115. return false
  1116. }); err != nil {
  1117. return err
  1118. }
  1119. // Update schema
  1120. return m.updateSchemaUnsafe(schema)
  1121. }
  1122. // rewriteRows applies an idempotent name-keyed row transformation in bounded
  1123. // batches. Column DDL updates the schema only after all rows are rewritten, so
  1124. // an interrupted operation can safely resume against the old schema.
  1125. func (m *SchemaManager) rewriteRows(table string, transform func(Row) bool) error {
  1126. prefix := []byte(fmt.Sprintf("%s:_data:%s:", m.database, strings.ToLower(table)))
  1127. return m.pool.WithClient(func(client *KVClient) (retErr error) {
  1128. cursor, err := client.Scan(prefix)
  1129. if err != nil {
  1130. return err
  1131. }
  1132. defer func() {
  1133. if cerr := cursor.Close(); retErr == nil {
  1134. retErr = cerr
  1135. }
  1136. }()
  1137. ops := make([]BatchOp, 0, scanPageSize)
  1138. batchBytes := 8
  1139. flush := func() error {
  1140. if len(ops) == 0 {
  1141. return nil
  1142. }
  1143. if _, err := client.BatchWrite(ops, nil); err != nil {
  1144. return err
  1145. }
  1146. ops = ops[:0]
  1147. batchBytes = 8
  1148. return nil
  1149. }
  1150. for {
  1151. entries, done, err := cursor.Next()
  1152. if err != nil {
  1153. return err
  1154. }
  1155. for _, entry := range entries {
  1156. row, err := decodeRow(entry.Value)
  1157. if err != nil {
  1158. return err
  1159. }
  1160. if !transform(row) {
  1161. continue
  1162. }
  1163. value, err := encodeRow(row)
  1164. if err != nil {
  1165. return err
  1166. }
  1167. opBytes := 12 + len(entry.Key) + len(value)
  1168. if len(ops) == maxOperations || batchBytes+opBytes > bulkBatchByteBudget {
  1169. if err := flush(); err != nil {
  1170. return err
  1171. }
  1172. }
  1173. ops = append(ops, BatchOp{Op: batchPut, Key: append([]byte(nil), entry.Key...), Value: value})
  1174. batchBytes += opBytes
  1175. }
  1176. if done {
  1177. return flush()
  1178. }
  1179. }
  1180. })
  1181. }
  1182. // getSchemaUnsafe gets a schema without locking (internal use).
  1183. func (m *SchemaManager) getSchemaUnsafe(table string) (*Schema, error) {
  1184. tableLower := strings.ToLower(table)
  1185. // Check cache
  1186. if schema, ok := m.cache[tableLower]; ok {
  1187. return schema, nil
  1188. }
  1189. // Read from storage
  1190. key := m.schemaKey(table)
  1191. var data string
  1192. err := m.pool.WithClient(func(c *KVClient) error {
  1193. var err error
  1194. data, err = c.Read(key)
  1195. return err
  1196. })
  1197. if err != nil {
  1198. return nil, fmt.Errorf("table not found: %s", table)
  1199. }
  1200. var schema Schema
  1201. if err := json.Unmarshal([]byte(data), &schema); err != nil {
  1202. return nil, err
  1203. }
  1204. m.cache[tableLower] = &schema
  1205. return &schema, nil
  1206. }
  1207. // updateSchemaUnsafe updates a schema without locking (internal use).
  1208. func (m *SchemaManager) updateSchemaUnsafe(schema *Schema) error {
  1209. key := m.schemaKey(schema.Name)
  1210. data, _ := json.Marshal(schema)
  1211. err := m.pool.WithClient(func(c *KVClient) error {
  1212. return c.Write(key, string(data))
  1213. })
  1214. if err != nil {
  1215. return err
  1216. }
  1217. // Update cache
  1218. m.cache[strings.ToLower(schema.Name)] = schema
  1219. m.bumpVersionLocked()
  1220. return nil
  1221. }