schema.go 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451
  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. // updateIndexesOfTableLocked applies mutate to the durable definition of every
  1013. // index on table and persists the definitions it changed. mutate reports
  1014. // whether it modified the definition; unmodified indexes are left untouched.
  1015. // The changed definitions are written in one batch, so a table's indexes never
  1016. // split between the old and new shape. The caller holds m.mu; it reads the
  1017. // durable index list directly rather than calling the self-locking ListIndexes
  1018. // helper.
  1019. func (m *SchemaManager) updateIndexesOfTableLocked(table string, mutate func(*Index) bool) error {
  1020. var names []string
  1021. if m.indexListCached {
  1022. names = append([]string(nil), m.indexListCache...)
  1023. } else {
  1024. var data string
  1025. err := m.pool.WithClient(func(c *KVClient) error {
  1026. var rerr error
  1027. data, rerr = c.Read(m.indexListKey())
  1028. return rerr
  1029. })
  1030. if err == ErrKeyNotFound {
  1031. return nil
  1032. }
  1033. if err != nil {
  1034. return err
  1035. }
  1036. if err := json.Unmarshal([]byte(data), &names); err != nil {
  1037. return err
  1038. }
  1039. }
  1040. type indexUpdate struct {
  1041. index Index
  1042. key string
  1043. value []byte
  1044. }
  1045. var updates []indexUpdate
  1046. for _, name := range names {
  1047. key := m.indexKey(name)
  1048. var data string
  1049. err := m.pool.WithClient(func(c *KVClient) error {
  1050. var rerr error
  1051. data, rerr = c.Read(key)
  1052. return rerr
  1053. })
  1054. if err != nil {
  1055. if err == ErrKeyNotFound {
  1056. continue
  1057. }
  1058. return err
  1059. }
  1060. var idx Index
  1061. if err := json.Unmarshal([]byte(data), &idx); err != nil {
  1062. return err
  1063. }
  1064. if !strings.EqualFold(idx.Table, table) {
  1065. continue
  1066. }
  1067. if !mutate(&idx) {
  1068. continue
  1069. }
  1070. updated, err := json.Marshal(&idx)
  1071. if err != nil {
  1072. return err
  1073. }
  1074. updates = append(updates, indexUpdate{index: idx, key: key, value: updated})
  1075. }
  1076. if len(updates) == 0 {
  1077. return nil
  1078. }
  1079. ops := make([]BatchOp, 0, len(updates))
  1080. for _, update := range updates {
  1081. ops = append(ops, BatchOp{Op: batchPut, Key: []byte(update.key), Value: update.value})
  1082. }
  1083. if err := m.pool.WithClient(func(c *KVClient) error {
  1084. _, err := c.BatchWrite(ops, nil)
  1085. return err
  1086. }); err != nil {
  1087. return fmt.Errorf("update index definitions for table %s: %w", table, err)
  1088. }
  1089. for _, update := range updates {
  1090. if cached, ok := m.indexCache[strings.ToLower(update.index.Name)]; ok {
  1091. *cached = update.index
  1092. }
  1093. }
  1094. return nil
  1095. }
  1096. // repointIndexesLocked updates indexes whose table was renamed.
  1097. func (m *SchemaManager) repointIndexesLocked(oldName, newName string) error {
  1098. return m.updateIndexesOfTableLocked(oldName, func(idx *Index) bool {
  1099. idx.Table = newName
  1100. return true
  1101. })
  1102. }
  1103. // renameIndexColumnsLocked rewrites the stored definition of every index on
  1104. // table so a reference to oldName becomes newName. Index names stay unchanged:
  1105. // they are independent identifiers that SQLite does not derive from column
  1106. // names, and callers may have chosen them explicitly. A rename to an existing
  1107. // column name is rejected before this runs. Expression columns keep their SQL
  1108. // text; callers must reject a rename that such an expression depends on,
  1109. // because the text is not rewritten.
  1110. func (m *SchemaManager) renameIndexColumnsLocked(table, oldName, newName string) error {
  1111. return m.updateIndexesOfTableLocked(table, func(idx *Index) bool {
  1112. changed := false
  1113. for i := range idx.Columns {
  1114. // Expression columns persist SQL text, not a column reference; their
  1115. // text is left for the caller to drop and recreate the index.
  1116. if idx.Columns[i].Expression == "" && strings.EqualFold(idx.Columns[i].Name, oldName) {
  1117. idx.Columns[i].Name = newName
  1118. changed = true
  1119. }
  1120. }
  1121. return changed
  1122. })
  1123. }
  1124. // RenameColumn renames a column in a table. Column references in index
  1125. // definitions are rewritten; expression-index text is not, so a SQL caller must
  1126. // reject a rename that an expression depends on.
  1127. func (m *SchemaManager) RenameColumn(table, oldName, newName string) error {
  1128. tableLock := m.tableLock(table)
  1129. tableLock.Lock()
  1130. defer tableLock.Unlock()
  1131. m.mu.Lock()
  1132. defer m.mu.Unlock()
  1133. schema, err := m.getSchemaUnsafe(table)
  1134. if err != nil {
  1135. return err
  1136. }
  1137. // Check if new column name already exists
  1138. for _, col := range schema.Columns {
  1139. if strings.EqualFold(col.Name, newName) {
  1140. return fmt.Errorf("column already exists: %s", newName)
  1141. }
  1142. }
  1143. schema = cloneSchema(schema)
  1144. // Find and rename column
  1145. found := false
  1146. for i, col := range schema.Columns {
  1147. if strings.EqualFold(col.Name, oldName) {
  1148. schema.Columns[i].Name = newName
  1149. found = true
  1150. // Update primary key reference if needed
  1151. if strings.EqualFold(schema.PrimaryKey, oldName) {
  1152. schema.PrimaryKey = newName
  1153. }
  1154. break
  1155. }
  1156. }
  1157. if !found {
  1158. return fmt.Errorf("column not found: %s", oldName)
  1159. }
  1160. if err := m.rewriteRows(table, func(row Row) bool {
  1161. for key, value := range row {
  1162. if strings.EqualFold(key, oldName) {
  1163. delete(row, key)
  1164. row[newName] = value
  1165. return true
  1166. }
  1167. }
  1168. return false
  1169. }); err != nil {
  1170. return err
  1171. }
  1172. // Publish the renamed schema before the index definitions: reads of the new
  1173. // column name resolve against rewritten rows as soon as the schema lands.
  1174. // Index DDL is not transactional (as elsewhere in this engine), so a failure
  1175. // here leaves stale index metadata for the caller to drop and recreate.
  1176. if err := m.updateSchemaUnsafe(schema); err != nil {
  1177. return err
  1178. }
  1179. // Index metadata drives secondary-index values, UNIQUE enforcement,
  1180. // ON CONFLICT target resolution, and catalog introspection, so it must name
  1181. // the renamed column before any later statement uses the table.
  1182. return m.renameIndexColumnsLocked(table, oldName, newName)
  1183. }
  1184. // rewriteRows applies an idempotent name-keyed row transformation in bounded
  1185. // batches. Column DDL updates the schema only after all rows are rewritten, so
  1186. // an interrupted operation can safely resume against the old schema.
  1187. func (m *SchemaManager) rewriteRows(table string, transform func(Row) bool) error {
  1188. prefix := []byte(fmt.Sprintf("%s:_data:%s:", m.database, strings.ToLower(table)))
  1189. return m.pool.WithClient(func(client *KVClient) (retErr error) {
  1190. cursor, err := client.Scan(prefix)
  1191. if err != nil {
  1192. return err
  1193. }
  1194. defer func() {
  1195. if cerr := cursor.Close(); retErr == nil {
  1196. retErr = cerr
  1197. }
  1198. }()
  1199. ops := make([]BatchOp, 0, scanPageSize)
  1200. batchBytes := 8
  1201. flush := func() error {
  1202. if len(ops) == 0 {
  1203. return nil
  1204. }
  1205. if _, err := client.BatchWrite(ops, nil); err != nil {
  1206. return err
  1207. }
  1208. ops = ops[:0]
  1209. batchBytes = 8
  1210. return nil
  1211. }
  1212. for {
  1213. entries, done, err := cursor.Next()
  1214. if err != nil {
  1215. return err
  1216. }
  1217. for _, entry := range entries {
  1218. row, err := decodeRow(entry.Value)
  1219. if err != nil {
  1220. return err
  1221. }
  1222. if !transform(row) {
  1223. continue
  1224. }
  1225. value, err := encodeRow(row)
  1226. if err != nil {
  1227. return err
  1228. }
  1229. opBytes := 12 + len(entry.Key) + len(value)
  1230. if len(ops) == maxOperations || batchBytes+opBytes > bulkBatchByteBudget {
  1231. if err := flush(); err != nil {
  1232. return err
  1233. }
  1234. }
  1235. ops = append(ops, BatchOp{Op: batchPut, Key: append([]byte(nil), entry.Key...), Value: value})
  1236. batchBytes += opBytes
  1237. }
  1238. if done {
  1239. return flush()
  1240. }
  1241. }
  1242. })
  1243. }
  1244. // getSchemaUnsafe gets a schema without locking (internal use).
  1245. func (m *SchemaManager) getSchemaUnsafe(table string) (*Schema, error) {
  1246. tableLower := strings.ToLower(table)
  1247. // Check cache
  1248. if schema, ok := m.cache[tableLower]; ok {
  1249. return schema, nil
  1250. }
  1251. // Read from storage
  1252. key := m.schemaKey(table)
  1253. var data string
  1254. err := m.pool.WithClient(func(c *KVClient) error {
  1255. var err error
  1256. data, err = c.Read(key)
  1257. return err
  1258. })
  1259. if err != nil {
  1260. return nil, fmt.Errorf("table not found: %s", table)
  1261. }
  1262. var schema Schema
  1263. if err := json.Unmarshal([]byte(data), &schema); err != nil {
  1264. return nil, err
  1265. }
  1266. m.cache[tableLower] = &schema
  1267. return &schema, nil
  1268. }
  1269. // updateSchemaUnsafe updates a schema without locking (internal use).
  1270. func (m *SchemaManager) updateSchemaUnsafe(schema *Schema) error {
  1271. key := m.schemaKey(schema.Name)
  1272. data, _ := json.Marshal(schema)
  1273. err := m.pool.WithClient(func(c *KVClient) error {
  1274. return c.Write(key, string(data))
  1275. })
  1276. if err != nil {
  1277. return err
  1278. }
  1279. // Update cache
  1280. m.cache[strings.ToLower(schema.Name)] = schema
  1281. m.bumpVersionLocked()
  1282. return nil
  1283. }