schema.go 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574
  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. return m.indexExistsUnsafe(name)
  671. }
  672. // indexExistsUnsafe reports whether an index definition is durable (m.mu must be
  673. // held).
  674. func (m *SchemaManager) indexExistsUnsafe(name string) bool {
  675. if _, ok := m.indexCache[strings.ToLower(name)]; ok {
  676. return true
  677. }
  678. key := m.indexKey(name)
  679. err := m.pool.WithClient(func(c *KVClient) error {
  680. _, err := c.Read(key)
  681. return err
  682. })
  683. return err == nil
  684. }
  685. // GetIndex retrieves an index by name.
  686. func (m *SchemaManager) GetIndex(name string) (*Index, error) {
  687. m.mu.Lock()
  688. defer m.mu.Unlock()
  689. cacheKey := strings.ToLower(name)
  690. if index, ok := m.indexCache[cacheKey]; ok {
  691. return cloneIndex(index), nil
  692. }
  693. key := m.indexKey(name)
  694. var data string
  695. err := m.pool.WithClient(func(c *KVClient) error {
  696. var err error
  697. data, err = c.Read(key)
  698. return err
  699. })
  700. if err != nil {
  701. if err == ErrKeyNotFound {
  702. return nil, fmt.Errorf("%w: %s", ErrIndexNotFound, name)
  703. }
  704. return nil, err
  705. }
  706. var index Index
  707. if err := json.Unmarshal([]byte(data), &index); err != nil {
  708. return nil, fmt.Errorf("failed to parse index: %w", err)
  709. }
  710. m.indexCache[cacheKey] = &index
  711. return cloneIndex(&index), nil
  712. }
  713. // ListIndexes returns all index names.
  714. func (m *SchemaManager) ListIndexes() ([]string, error) {
  715. m.mu.Lock()
  716. defer m.mu.Unlock()
  717. return m.indexListUnsafe()
  718. }
  719. // indexListUnsafe returns all index names, loading them from storage on first
  720. // use (m.mu must be held).
  721. func (m *SchemaManager) indexListUnsafe() ([]string, error) {
  722. if m.indexListCached {
  723. return append([]string(nil), m.indexListCache...), nil
  724. }
  725. key := m.indexListKey()
  726. var data string
  727. err := m.pool.WithClient(func(c *KVClient) error {
  728. var err error
  729. data, err = c.Read(key)
  730. return err
  731. })
  732. if err == ErrKeyNotFound {
  733. m.indexListCache = nil
  734. m.indexListCached = true
  735. return []string{}, nil
  736. }
  737. if err != nil {
  738. return nil, err
  739. }
  740. var indexes []string
  741. if err := json.Unmarshal([]byte(data), &indexes); err != nil {
  742. return nil, fmt.Errorf("failed to parse index list: %w", err)
  743. }
  744. m.indexListCache = append([]string(nil), indexes...)
  745. m.indexListCached = true
  746. return indexes, nil
  747. }
  748. // ListTableIndexes returns all indexes for a table.
  749. func (m *SchemaManager) ListTableIndexes(table string) ([]*Index, error) {
  750. indexes, err := m.ListIndexes()
  751. if err != nil {
  752. return nil, err
  753. }
  754. var result []*Index
  755. for _, name := range indexes {
  756. idx, err := m.GetIndex(name)
  757. if err != nil {
  758. // An index dropped concurrently is simply absent; any other error
  759. // (storage/IO or corrupt data) must not be silently swallowed.
  760. if errors.Is(err, ErrIndexNotFound) {
  761. continue
  762. }
  763. return nil, err
  764. }
  765. if strings.EqualFold(idx.Table, table) {
  766. result = append(result, idx)
  767. }
  768. }
  769. return result, nil
  770. }
  771. // addToIndexList adds an index name to the list.
  772. func (m *SchemaManager) addToIndexList(name string) error {
  773. key := m.indexListKey()
  774. var indexes []string
  775. var data string
  776. err := m.pool.WithClient(func(c *KVClient) error {
  777. var err error
  778. data, err = c.Read(key)
  779. return err
  780. })
  781. if err == nil {
  782. json.Unmarshal([]byte(data), &indexes)
  783. }
  784. indexes = append(indexes, name)
  785. newData, _ := json.Marshal(indexes)
  786. err = m.pool.WithClient(func(c *KVClient) error {
  787. return c.Write(key, string(newData))
  788. })
  789. if err == nil {
  790. m.indexListCache = append([]string(nil), indexes...)
  791. m.indexListCached = true
  792. }
  793. return err
  794. }
  795. // removeFromIndexList removes an index name from the list.
  796. func (m *SchemaManager) removeFromIndexList(name string) error {
  797. key := m.indexListKey()
  798. var indexes []string
  799. var data string
  800. err := m.pool.WithClient(func(c *KVClient) error {
  801. var err error
  802. data, err = c.Read(key)
  803. return err
  804. })
  805. if err != nil {
  806. return nil
  807. }
  808. json.Unmarshal([]byte(data), &indexes)
  809. var newIndexes []string
  810. for _, idx := range indexes {
  811. if !strings.EqualFold(idx, name) {
  812. newIndexes = append(newIndexes, idx)
  813. }
  814. }
  815. newData, _ := json.Marshal(newIndexes)
  816. err = m.pool.WithClient(func(c *KVClient) error {
  817. return c.Write(key, string(newData))
  818. })
  819. if err == nil {
  820. m.indexListCache = append([]string(nil), newIndexes...)
  821. m.indexListCached = true
  822. }
  823. return err
  824. }
  825. // AddColumn adds a new column to a table. When unique is non-nil the column's
  826. // UNIQUE index is registered as part of the same statement.
  827. //
  828. // A constant DEFAULT is materialized into every existing row before the schema
  829. // is published. NOT NULL, UNIQUE, and index validation all read persisted row
  830. // values, so a default that only existed in the catalog would be invisible to
  831. // them: a UNIQUE index over the new column could not see the duplicate values
  832. // every existing row shares, and an UPDATE to NULL would look non-null. The
  833. // rewrite is the same shape as DropColumn: the table's exclusive gate keeps
  834. // point writes and CAS commits out while rows are scanned, validated, and
  835. // rewritten, the transform is idempotent, and the schema is saved last so an
  836. // interrupted operation resumes against the old schema.
  837. //
  838. // The gate also makes the validation authoritative: NOT NULL without a default
  839. // and duplicate UNIQUE values are rejected before any row is touched, and the
  840. // column and its index are published together in one batch write, so a crash
  841. // cannot leave the column visible without the constraint that validates it.
  842. // A nullable column without a default needs no rewrite because a missing row
  843. // field already reads as NULL. Like DROP COLUMN, the statement holds the catalog
  844. // lock for the whole scan, so the cost is one table scan (two for UNIQUE) and a
  845. // table-wide stall per ADD COLUMN that has a default or an index.
  846. func (m *SchemaManager) AddColumn(table string, column Column, unique *Index) error {
  847. tableLock := m.tableLock(table)
  848. tableLock.Lock()
  849. defer tableLock.Unlock()
  850. m.mu.Lock()
  851. defer m.mu.Unlock()
  852. schema, err := m.getSchemaUnsafe(table)
  853. if err != nil {
  854. return err
  855. }
  856. if err := checkColumnAbsent(schema, column.Name); err != nil {
  857. return err
  858. }
  859. if unique != nil {
  860. if !strings.EqualFold(unique.Table, schema.Name) {
  861. return fmt.Errorf("index %s belongs to table %s, not %s", unique.Name, unique.Table, schema.Name)
  862. }
  863. if m.indexExistsUnsafe(unique.Name) {
  864. return fmt.Errorf("index already exists: %s", unique.Name)
  865. }
  866. if err := m.validateAddColumnUnique(table, column, unique); err != nil {
  867. return err
  868. }
  869. }
  870. // A required column with nothing to write into rows that already exist
  871. // cannot be declared on a populated table.
  872. if !column.Nullable && column.Default == nil {
  873. hasRows, err := m.tableHasRows(table)
  874. if err != nil {
  875. return err
  876. }
  877. if hasRows {
  878. return &NotNullViolationError{Table: schema.Name, Column: column.Name}
  879. }
  880. }
  881. if column.Default != nil {
  882. if err := m.rewriteRows(table, func(row Row) bool {
  883. if _, ok := rowColumnValue(row, column.Name); ok {
  884. return false
  885. }
  886. row[column.Name] = column.Default
  887. return true
  888. }); err != nil {
  889. return err
  890. }
  891. }
  892. return m.publishAddedColumn(schema, column, unique)
  893. }
  894. // publishAddedColumn publishes a column and, when present, its unique index in
  895. // one atomic batch write (m.mu must be held): the schema snapshot, the index
  896. // definition, and the index list always become durable together or not at all.
  897. func (m *SchemaManager) publishAddedColumn(schema *Schema, column Column, unique *Index) error {
  898. // Publish a fresh snapshot instead of mutating readers' shared pointer.
  899. schema = cloneSchema(schema)
  900. schema.Columns = append(schema.Columns, column)
  901. schemaData, err := json.Marshal(schema)
  902. if err != nil {
  903. return fmt.Errorf("failed to serialize schema: %w", err)
  904. }
  905. ops := []BatchOp{{Op: batchPut, Key: []byte(m.schemaKey(schema.Name)), Value: schemaData}}
  906. var indexList []string
  907. if unique != nil {
  908. unique.CreatedAt = time.Now()
  909. indexData, err := json.Marshal(unique)
  910. if err != nil {
  911. return fmt.Errorf("failed to serialize index: %w", err)
  912. }
  913. indexList, err = m.indexListUnsafe()
  914. if err != nil {
  915. return err
  916. }
  917. indexList = append(indexList, unique.Name)
  918. listData, err := json.Marshal(indexList)
  919. if err != nil {
  920. return fmt.Errorf("failed to serialize index list: %w", err)
  921. }
  922. ops = append(ops,
  923. BatchOp{Op: batchPut, Key: []byte(m.indexKey(unique.Name)), Value: indexData},
  924. BatchOp{Op: batchPut, Key: []byte(m.indexListKey()), Value: listData},
  925. )
  926. }
  927. if err := m.pool.WithClient(func(c *KVClient) error {
  928. _, err := c.BatchWrite(ops, nil)
  929. return err
  930. }); err != nil {
  931. return fmt.Errorf("failed to publish column %s: %w", column.Name, err)
  932. }
  933. // Publish in-memory state only after the durable write.
  934. m.cache[strings.ToLower(schema.Name)] = schema
  935. if unique != nil {
  936. m.indexCache[strings.ToLower(unique.Name)] = cloneIndex(unique)
  937. m.indexListCache = append([]string(nil), indexList...)
  938. m.indexListCached = true
  939. }
  940. m.bumpVersionLocked()
  941. return nil
  942. }
  943. func checkColumnAbsent(schema *Schema, name string) error {
  944. for _, col := range schema.Columns {
  945. if strings.EqualFold(col.Name, name) {
  946. return fmt.Errorf("column already exists: %s", name)
  947. }
  948. }
  949. return nil
  950. }
  951. // DropColumn removes a column from a table.
  952. func (m *SchemaManager) DropColumn(table, columnName string) error {
  953. tableLock := m.tableLock(table)
  954. tableLock.Lock()
  955. defer tableLock.Unlock()
  956. m.mu.Lock()
  957. defer m.mu.Unlock()
  958. schema, err := m.getSchemaUnsafe(table)
  959. if err != nil {
  960. return err
  961. }
  962. // Cannot drop primary key column
  963. if strings.EqualFold(schema.PrimaryKey, columnName) {
  964. return fmt.Errorf("cannot drop primary key column: %s", columnName)
  965. }
  966. // Find and remove column
  967. newColumns := make([]Column, 0, len(schema.Columns)-1)
  968. found := false
  969. for _, col := range schema.Columns {
  970. if strings.EqualFold(col.Name, columnName) {
  971. found = true
  972. continue
  973. }
  974. newColumns = append(newColumns, col)
  975. }
  976. if !found {
  977. return fmt.Errorf("column not found: %s", columnName)
  978. }
  979. schema = cloneSchema(schema)
  980. schema.Columns = newColumns
  981. if err := m.rewriteRows(table, func(row Row) bool {
  982. for key := range row {
  983. if strings.EqualFold(key, columnName) {
  984. delete(row, key)
  985. return true
  986. }
  987. }
  988. return false
  989. }); err != nil {
  990. return err
  991. }
  992. // Update schema
  993. return m.updateSchemaUnsafe(schema)
  994. }
  995. // RenameTable renames a table.
  996. func (m *SchemaManager) RenameTable(oldName, newName string) error {
  997. m.mu.Lock()
  998. defer m.mu.Unlock()
  999. // Check if old table exists
  1000. schema, err := m.getSchemaUnsafe(oldName)
  1001. if err != nil {
  1002. return err
  1003. }
  1004. // Check if new table name already exists
  1005. _, err = m.getSchemaUnsafe(newName)
  1006. if err == nil {
  1007. return fmt.Errorf("table already exists: %s", newName)
  1008. }
  1009. schema = cloneSchema(schema)
  1010. // Update schema name
  1011. schema.Name = newName
  1012. // Move durable rows from the old table's data prefix to the new one. Without
  1013. // this, ALTER TABLE ... RENAME leaves every row under the old key and the
  1014. // renamed table appears empty.
  1015. if err := m.renameDataKeys(oldName, newName); err != nil {
  1016. return err
  1017. }
  1018. // Repoint indexes that belonged to the old table.
  1019. if err := m.repointIndexesLocked(oldName, newName); err != nil {
  1020. return err
  1021. }
  1022. // Build the replacement catalog before switching schema names. The schema,
  1023. // catalog, and stale ROWID state change in one batch, so a crash cannot
  1024. // leave neither table name addressable after all row chunks have moved.
  1025. tables, err := m.ListTables()
  1026. if err != nil {
  1027. return err
  1028. }
  1029. foundOld := false
  1030. for i, name := range tables {
  1031. if strings.EqualFold(name, oldName) {
  1032. tables[i] = newName
  1033. foundOld = true
  1034. break
  1035. }
  1036. }
  1037. if !foundOld {
  1038. return fmt.Errorf("table not found in catalog: %s", oldName)
  1039. }
  1040. catalogData, err := json.Marshal(tables)
  1041. if err != nil {
  1042. return err
  1043. }
  1044. schemaData, err := json.Marshal(schema)
  1045. if err != nil {
  1046. return err
  1047. }
  1048. oldKey := m.schemaKey(oldName)
  1049. newKey := m.schemaKey(newName)
  1050. err = m.pool.WithClient(func(c *KVClient) error {
  1051. _, err := c.BatchWrite([]BatchOp{
  1052. {Op: batchPut, Key: []byte(newKey), Value: schemaData},
  1053. {Op: batchDelete, Key: []byte(oldKey)},
  1054. {Op: batchDelete, Key: []byte(m.rowIDKey(oldName))},
  1055. {Op: batchPut, Key: []byte(m.catalogKey()), Value: catalogData},
  1056. }, nil)
  1057. return err
  1058. })
  1059. if err != nil {
  1060. return err
  1061. }
  1062. // Update cache
  1063. oldLower := strings.ToLower(oldName)
  1064. newLower := strings.ToLower(newName)
  1065. delete(m.cache, oldLower)
  1066. m.rowIDMu.Lock()
  1067. delete(m.rowIDAlloc, oldLower)
  1068. m.rowIDMu.Unlock()
  1069. // Update cache
  1070. m.cache[newLower] = schema
  1071. m.bumpVersionLocked()
  1072. return nil
  1073. }
  1074. // renameDataKeys moves every durable row of a table from the old name's data
  1075. // prefix to the new name's prefix in a single atomic batch per page.
  1076. func (m *SchemaManager) renameDataKeys(oldName, newName string) error {
  1077. oldPrefix := []byte(fmt.Sprintf("%s:_data:%s:", m.database, strings.ToLower(oldName)))
  1078. newPrefix := fmt.Sprintf("%s:_data:%s:", m.database, strings.ToLower(newName))
  1079. return m.pool.WithClient(func(client *KVClient) (retErr error) {
  1080. cursor, err := client.Scan(oldPrefix)
  1081. if err != nil {
  1082. return err
  1083. }
  1084. defer func() {
  1085. if cerr := cursor.Close(); retErr == nil {
  1086. retErr = cerr
  1087. }
  1088. }()
  1089. ops := make([]BatchOp, 0, scanPageSize*2)
  1090. batchBytes := 8
  1091. flush := func() error {
  1092. if len(ops) == 0 {
  1093. return nil
  1094. }
  1095. if _, err := client.BatchWrite(ops, nil); err != nil {
  1096. return err
  1097. }
  1098. ops = ops[:0]
  1099. batchBytes = 8
  1100. return nil
  1101. }
  1102. for {
  1103. entries, done, err := cursor.Next()
  1104. if err != nil {
  1105. return err
  1106. }
  1107. for _, e := range entries {
  1108. suffix := string(e.Key[len(oldPrefix):])
  1109. newKey := []byte(newPrefix + suffix)
  1110. opBytes := 24 + len(newKey) + len(e.Value) + len(e.Key)
  1111. if len(ops)+2 > maxOperations || batchBytes+opBytes > bulkBatchByteBudget {
  1112. if err := flush(); err != nil {
  1113. return err
  1114. }
  1115. }
  1116. ops = append(ops,
  1117. BatchOp{Op: batchPut, Key: newKey, Value: e.Value},
  1118. BatchOp{Op: batchDelete, Key: append([]byte(nil), e.Key...)},
  1119. )
  1120. batchBytes += opBytes
  1121. }
  1122. if done {
  1123. return flush()
  1124. }
  1125. }
  1126. })
  1127. }
  1128. // repointIndexesLocked updates indexes whose table was renamed. The caller holds
  1129. // m.mu; it reads the durable index list directly rather than calling the
  1130. // self-locking ListIndexes helper.
  1131. func (m *SchemaManager) repointIndexesLocked(oldName, newName string) error {
  1132. var names []string
  1133. if m.indexListCached {
  1134. names = append([]string(nil), m.indexListCache...)
  1135. } else {
  1136. var data string
  1137. err := m.pool.WithClient(func(c *KVClient) error {
  1138. var rerr error
  1139. data, rerr = c.Read(m.indexListKey())
  1140. return rerr
  1141. })
  1142. if err == ErrKeyNotFound {
  1143. return nil
  1144. }
  1145. if err != nil {
  1146. return err
  1147. }
  1148. if err := json.Unmarshal([]byte(data), &names); err != nil {
  1149. return err
  1150. }
  1151. }
  1152. for _, name := range names {
  1153. key := m.indexKey(name)
  1154. var data string
  1155. err := m.pool.WithClient(func(c *KVClient) error {
  1156. var rerr error
  1157. data, rerr = c.Read(key)
  1158. return rerr
  1159. })
  1160. if err != nil {
  1161. if err == ErrKeyNotFound {
  1162. continue
  1163. }
  1164. return err
  1165. }
  1166. var idx Index
  1167. if err := json.Unmarshal([]byte(data), &idx); err != nil {
  1168. return err
  1169. }
  1170. if !strings.EqualFold(idx.Table, oldName) {
  1171. continue
  1172. }
  1173. idx.Table = newName
  1174. updated, err := json.Marshal(&idx)
  1175. if err != nil {
  1176. return err
  1177. }
  1178. if err := m.pool.WithClient(func(c *KVClient) error {
  1179. return c.Write(key, string(updated))
  1180. }); err != nil {
  1181. return err
  1182. }
  1183. if cached, ok := m.indexCache[strings.ToLower(name)]; ok {
  1184. cached.Table = newName
  1185. }
  1186. }
  1187. return nil
  1188. }
  1189. // RenameColumn renames a column in a table.
  1190. func (m *SchemaManager) RenameColumn(table, oldName, newName string) error {
  1191. tableLock := m.tableLock(table)
  1192. tableLock.Lock()
  1193. defer tableLock.Unlock()
  1194. m.mu.Lock()
  1195. defer m.mu.Unlock()
  1196. schema, err := m.getSchemaUnsafe(table)
  1197. if err != nil {
  1198. return err
  1199. }
  1200. // Check if new column name already exists
  1201. for _, col := range schema.Columns {
  1202. if strings.EqualFold(col.Name, newName) {
  1203. return fmt.Errorf("column already exists: %s", newName)
  1204. }
  1205. }
  1206. schema = cloneSchema(schema)
  1207. // Find and rename column
  1208. found := false
  1209. for i, col := range schema.Columns {
  1210. if strings.EqualFold(col.Name, oldName) {
  1211. schema.Columns[i].Name = newName
  1212. found = true
  1213. // Update primary key reference if needed
  1214. if strings.EqualFold(schema.PrimaryKey, oldName) {
  1215. schema.PrimaryKey = newName
  1216. }
  1217. break
  1218. }
  1219. }
  1220. if !found {
  1221. return fmt.Errorf("column not found: %s", oldName)
  1222. }
  1223. if err := m.rewriteRows(table, func(row Row) bool {
  1224. for key, value := range row {
  1225. if strings.EqualFold(key, oldName) {
  1226. delete(row, key)
  1227. row[newName] = value
  1228. return true
  1229. }
  1230. }
  1231. return false
  1232. }); err != nil {
  1233. return err
  1234. }
  1235. // Update schema
  1236. return m.updateSchemaUnsafe(schema)
  1237. }
  1238. // rewriteRows applies an idempotent name-keyed row transformation in bounded
  1239. // batches. Column DDL updates the schema only after all rows are rewritten, so
  1240. // an interrupted operation can safely resume against the old schema.
  1241. func (m *SchemaManager) rewriteRows(table string, transform func(Row) bool) error {
  1242. return m.applyRows(table, func(row Row) (bool, error) {
  1243. return transform(row), nil
  1244. })
  1245. }
  1246. // applyRows scans a table once and applies transform to every row. Rows for
  1247. // which transform reports a change are re-encoded and written in bounded
  1248. // batches; an error from transform aborts the scan. Callers hold the table's
  1249. // exclusive gate, so no writer can interleave between the scan and the schema
  1250. // update that follows it. Aborting after a batch was flushed is safe only
  1251. // because the DDL transforms are idempotent.
  1252. func (m *SchemaManager) applyRows(table string, transform func(Row) (bool, error)) error {
  1253. prefix := []byte(fmt.Sprintf("%s:_data:%s:", m.database, strings.ToLower(table)))
  1254. return m.pool.WithClient(func(client *KVClient) (retErr error) {
  1255. cursor, err := client.Scan(prefix)
  1256. if err != nil {
  1257. return err
  1258. }
  1259. defer func() {
  1260. if cerr := cursor.Close(); retErr == nil {
  1261. retErr = cerr
  1262. }
  1263. }()
  1264. ops := make([]BatchOp, 0, scanPageSize)
  1265. batchBytes := 8
  1266. flush := func() error {
  1267. if len(ops) == 0 {
  1268. return nil
  1269. }
  1270. if _, err := client.BatchWrite(ops, nil); err != nil {
  1271. return err
  1272. }
  1273. ops = ops[:0]
  1274. batchBytes = 8
  1275. return nil
  1276. }
  1277. for {
  1278. entries, done, err := cursor.Next()
  1279. if err != nil {
  1280. return err
  1281. }
  1282. for _, entry := range entries {
  1283. row, err := decodeRow(entry.Value)
  1284. if err != nil {
  1285. return err
  1286. }
  1287. changed, err := transform(row)
  1288. if err != nil {
  1289. return err
  1290. }
  1291. if !changed {
  1292. continue
  1293. }
  1294. value, err := encodeRow(row)
  1295. if err != nil {
  1296. return err
  1297. }
  1298. opBytes := 12 + len(entry.Key) + len(value)
  1299. if len(ops) == maxOperations || batchBytes+opBytes > bulkBatchByteBudget {
  1300. if err := flush(); err != nil {
  1301. return err
  1302. }
  1303. }
  1304. ops = append(ops, BatchOp{Op: batchPut, Key: append([]byte(nil), entry.Key...), Value: value})
  1305. batchBytes += opBytes
  1306. }
  1307. if done {
  1308. return flush()
  1309. }
  1310. }
  1311. })
  1312. }
  1313. // validateAddColumnUnique rejects an ADD COLUMN ... UNIQUE whose backfilled
  1314. // values would duplicate across existing rows. It reads rows as they will look
  1315. // after the rewrite (a row that already carries the field from an interrupted
  1316. // earlier attempt keeps its value) and mirrors ValidateUniqueIndex for a single
  1317. // plain column: NULLs do not collide. The caller holds the table's exclusive
  1318. // gate, so no writer can insert a conflicting row between this check and the
  1319. // publication of the index.
  1320. func (m *SchemaManager) validateAddColumnUnique(table string, column Column, index *Index) error {
  1321. seen := make(map[string]struct{})
  1322. return m.applyRows(table, func(row Row) (bool, error) {
  1323. value, ok := rowColumnValue(row, column.Name)
  1324. if !ok {
  1325. value = column.Default
  1326. }
  1327. if value == nil {
  1328. return false, nil
  1329. }
  1330. encoded := encodeUniqueScalar(value)
  1331. if _, duplicate := seen[encoded]; duplicate {
  1332. return false, &UniqueViolationError{Constraint: index.Name}
  1333. }
  1334. seen[encoded] = struct{}{}
  1335. return false, nil
  1336. })
  1337. }
  1338. // tableHasRows reports whether a table holds at least one durable row.
  1339. func (m *SchemaManager) tableHasRows(table string) (bool, error) {
  1340. prefix := []byte(fmt.Sprintf("%s:_data:%s:", m.database, strings.ToLower(table)))
  1341. found := false
  1342. err := m.pool.WithClient(func(client *KVClient) (retErr error) {
  1343. cursor, err := client.ScanWithLimit(prefix, 1)
  1344. if err != nil {
  1345. return err
  1346. }
  1347. defer func() {
  1348. if cerr := cursor.Close(); retErr == nil {
  1349. retErr = cerr
  1350. }
  1351. }()
  1352. entries, _, err := cursor.Next()
  1353. if err != nil {
  1354. return err
  1355. }
  1356. found = len(entries) > 0
  1357. return nil
  1358. })
  1359. return found, err
  1360. }
  1361. // getSchemaUnsafe gets a schema without locking (internal use).
  1362. func (m *SchemaManager) getSchemaUnsafe(table string) (*Schema, error) {
  1363. tableLower := strings.ToLower(table)
  1364. // Check cache
  1365. if schema, ok := m.cache[tableLower]; ok {
  1366. return schema, nil
  1367. }
  1368. // Read from storage
  1369. key := m.schemaKey(table)
  1370. var data string
  1371. err := m.pool.WithClient(func(c *KVClient) error {
  1372. var err error
  1373. data, err = c.Read(key)
  1374. return err
  1375. })
  1376. if err != nil {
  1377. return nil, fmt.Errorf("table not found: %s", table)
  1378. }
  1379. var schema Schema
  1380. if err := json.Unmarshal([]byte(data), &schema); err != nil {
  1381. return nil, err
  1382. }
  1383. m.cache[tableLower] = &schema
  1384. return &schema, nil
  1385. }
  1386. // updateSchemaUnsafe updates a schema without locking (internal use).
  1387. func (m *SchemaManager) updateSchemaUnsafe(schema *Schema) error {
  1388. key := m.schemaKey(schema.Name)
  1389. data, _ := json.Marshal(schema)
  1390. err := m.pool.WithClient(func(c *KVClient) error {
  1391. return c.Write(key, string(data))
  1392. })
  1393. if err != nil {
  1394. return err
  1395. }
  1396. // Update cache
  1397. m.cache[strings.ToLower(schema.Name)] = schema
  1398. m.bumpVersionLocked()
  1399. return nil
  1400. }