schema.go 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641
  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. // updateIndexesOfTableLocked applies mutate to the durable definition of every
  1129. // index on table and persists the definitions it changed. mutate reports
  1130. // whether it modified the definition; unmodified indexes are left untouched.
  1131. // The changed definitions are written in one batch, so a table's indexes never
  1132. // split between the old and new shape. The caller holds m.mu; it reads the
  1133. // durable index list directly rather than calling the self-locking ListIndexes
  1134. // helper.
  1135. func (m *SchemaManager) updateIndexesOfTableLocked(table string, mutate func(*Index) bool) error {
  1136. var names []string
  1137. if m.indexListCached {
  1138. names = append([]string(nil), m.indexListCache...)
  1139. } else {
  1140. var data string
  1141. err := m.pool.WithClient(func(c *KVClient) error {
  1142. var rerr error
  1143. data, rerr = c.Read(m.indexListKey())
  1144. return rerr
  1145. })
  1146. if err == ErrKeyNotFound {
  1147. return nil
  1148. }
  1149. if err != nil {
  1150. return err
  1151. }
  1152. if err := json.Unmarshal([]byte(data), &names); err != nil {
  1153. return err
  1154. }
  1155. }
  1156. type indexUpdate struct {
  1157. index Index
  1158. key string
  1159. value []byte
  1160. }
  1161. var updates []indexUpdate
  1162. for _, name := range names {
  1163. key := m.indexKey(name)
  1164. var data string
  1165. err := m.pool.WithClient(func(c *KVClient) error {
  1166. var rerr error
  1167. data, rerr = c.Read(key)
  1168. return rerr
  1169. })
  1170. if err != nil {
  1171. if err == ErrKeyNotFound {
  1172. continue
  1173. }
  1174. return err
  1175. }
  1176. var idx Index
  1177. if err := json.Unmarshal([]byte(data), &idx); err != nil {
  1178. return err
  1179. }
  1180. if !strings.EqualFold(idx.Table, table) {
  1181. continue
  1182. }
  1183. if !mutate(&idx) {
  1184. continue
  1185. }
  1186. updated, err := json.Marshal(&idx)
  1187. if err != nil {
  1188. return err
  1189. }
  1190. updates = append(updates, indexUpdate{index: idx, key: key, value: updated})
  1191. }
  1192. if len(updates) == 0 {
  1193. return nil
  1194. }
  1195. ops := make([]BatchOp, 0, len(updates))
  1196. for _, update := range updates {
  1197. ops = append(ops, BatchOp{Op: batchPut, Key: []byte(update.key), Value: update.value})
  1198. }
  1199. if err := m.pool.WithClient(func(c *KVClient) error {
  1200. _, err := c.BatchWrite(ops, nil)
  1201. return err
  1202. }); err != nil {
  1203. return fmt.Errorf("update index definitions for table %s: %w", table, err)
  1204. }
  1205. for _, update := range updates {
  1206. if cached, ok := m.indexCache[strings.ToLower(update.index.Name)]; ok {
  1207. *cached = update.index
  1208. }
  1209. }
  1210. return nil
  1211. }
  1212. // repointIndexesLocked updates indexes whose table was renamed.
  1213. func (m *SchemaManager) repointIndexesLocked(oldName, newName string) error {
  1214. return m.updateIndexesOfTableLocked(oldName, func(idx *Index) bool {
  1215. idx.Table = newName
  1216. return true
  1217. })
  1218. }
  1219. // renameIndexColumnsLocked rewrites the stored definition of every index on
  1220. // table so a reference to oldName becomes newName. Index names stay unchanged:
  1221. // they are independent identifiers that SQLite does not derive from column
  1222. // names, and callers may have chosen them explicitly. A rename to an existing
  1223. // column name is rejected before this runs. Expression columns keep their SQL
  1224. // text; callers must reject a rename that such an expression depends on,
  1225. // because the text is not rewritten.
  1226. func (m *SchemaManager) renameIndexColumnsLocked(table, oldName, newName string) error {
  1227. return m.updateIndexesOfTableLocked(table, func(idx *Index) bool {
  1228. changed := false
  1229. for i := range idx.Columns {
  1230. // Expression columns persist SQL text, not a column reference; their
  1231. // text is left for the caller to drop and recreate the index.
  1232. if idx.Columns[i].Expression == "" && strings.EqualFold(idx.Columns[i].Name, oldName) {
  1233. idx.Columns[i].Name = newName
  1234. changed = true
  1235. }
  1236. }
  1237. return changed
  1238. })
  1239. }
  1240. // RenameColumn renames a column in a table. Column references in index
  1241. // definitions are rewritten; expression-index text is not, so a SQL caller must
  1242. // reject a rename that an expression depends on.
  1243. func (m *SchemaManager) RenameColumn(table, oldName, newName string) error {
  1244. tableLock := m.tableLock(table)
  1245. tableLock.Lock()
  1246. defer tableLock.Unlock()
  1247. m.mu.Lock()
  1248. defer m.mu.Unlock()
  1249. schema, err := m.getSchemaUnsafe(table)
  1250. if err != nil {
  1251. return err
  1252. }
  1253. // Check if new column name already exists
  1254. for _, col := range schema.Columns {
  1255. if strings.EqualFold(col.Name, newName) {
  1256. return fmt.Errorf("column already exists: %s", newName)
  1257. }
  1258. }
  1259. schema = cloneSchema(schema)
  1260. // Find and rename column
  1261. found := false
  1262. for i, col := range schema.Columns {
  1263. if strings.EqualFold(col.Name, oldName) {
  1264. schema.Columns[i].Name = newName
  1265. found = true
  1266. // Update primary key reference if needed
  1267. if strings.EqualFold(schema.PrimaryKey, oldName) {
  1268. schema.PrimaryKey = newName
  1269. }
  1270. break
  1271. }
  1272. }
  1273. if !found {
  1274. return fmt.Errorf("column not found: %s", oldName)
  1275. }
  1276. if err := m.rewriteRows(table, func(row Row) bool {
  1277. for key, value := range row {
  1278. if strings.EqualFold(key, oldName) {
  1279. delete(row, key)
  1280. row[newName] = value
  1281. return true
  1282. }
  1283. }
  1284. return false
  1285. }); err != nil {
  1286. return err
  1287. }
  1288. // Publish the renamed schema before the index definitions: reads of the new
  1289. // column name resolve against rewritten rows as soon as the schema lands.
  1290. // Index DDL is not transactional (as elsewhere in this engine), so a failure
  1291. // here leaves stale index metadata for the caller to drop and recreate.
  1292. if err := m.updateSchemaUnsafe(schema); err != nil {
  1293. return err
  1294. }
  1295. // Index metadata drives secondary-index values, UNIQUE enforcement,
  1296. // ON CONFLICT target resolution, and catalog introspection, so it must name
  1297. // the renamed column before any later statement uses the table.
  1298. return m.renameIndexColumnsLocked(table, oldName, newName)
  1299. }
  1300. // rewriteRows applies an idempotent name-keyed row transformation in bounded
  1301. // batches. Column DDL updates the schema only after all rows are rewritten, so
  1302. // an interrupted operation can safely resume against the old schema.
  1303. func (m *SchemaManager) rewriteRows(table string, transform func(Row) bool) error {
  1304. return m.applyRows(table, func(row Row) (bool, error) {
  1305. return transform(row), nil
  1306. })
  1307. }
  1308. // applyRows scans a table once and applies transform to every row. Rows for
  1309. // which transform reports a change are re-encoded and written in bounded
  1310. // batches; an error from transform aborts the scan. Callers hold the table's
  1311. // exclusive gate, so no writer can interleave between the scan and the schema
  1312. // update that follows it. Aborting after a batch was flushed is safe only
  1313. // because the DDL transforms are idempotent.
  1314. func (m *SchemaManager) applyRows(table string, transform func(Row) (bool, error)) error {
  1315. prefix := []byte(fmt.Sprintf("%s:_data:%s:", m.database, strings.ToLower(table)))
  1316. return m.pool.WithClient(func(client *KVClient) (retErr error) {
  1317. cursor, err := client.Scan(prefix)
  1318. if err != nil {
  1319. return err
  1320. }
  1321. defer func() {
  1322. if cerr := cursor.Close(); retErr == nil {
  1323. retErr = cerr
  1324. }
  1325. }()
  1326. ops := make([]BatchOp, 0, scanPageSize)
  1327. batchBytes := 8
  1328. flush := func() error {
  1329. if len(ops) == 0 {
  1330. return nil
  1331. }
  1332. if _, err := client.BatchWrite(ops, nil); err != nil {
  1333. return err
  1334. }
  1335. ops = ops[:0]
  1336. batchBytes = 8
  1337. return nil
  1338. }
  1339. for {
  1340. entries, done, err := cursor.Next()
  1341. if err != nil {
  1342. return err
  1343. }
  1344. for _, entry := range entries {
  1345. row, err := decodeRow(entry.Value)
  1346. if err != nil {
  1347. return err
  1348. }
  1349. changed, err := transform(row)
  1350. if err != nil {
  1351. return err
  1352. }
  1353. if !changed {
  1354. continue
  1355. }
  1356. value, err := encodeRow(row)
  1357. if err != nil {
  1358. return err
  1359. }
  1360. opBytes := 12 + len(entry.Key) + len(value)
  1361. if len(ops) == maxOperations || batchBytes+opBytes > bulkBatchByteBudget {
  1362. if err := flush(); err != nil {
  1363. return err
  1364. }
  1365. }
  1366. ops = append(ops, BatchOp{Op: batchPut, Key: append([]byte(nil), entry.Key...), Value: value})
  1367. batchBytes += opBytes
  1368. }
  1369. if done {
  1370. return flush()
  1371. }
  1372. }
  1373. })
  1374. }
  1375. // validateAddColumnUnique rejects an ADD COLUMN ... UNIQUE whose backfilled
  1376. // values would duplicate across existing rows. It reads rows as they will look
  1377. // after the rewrite (a row that already carries the field from an interrupted
  1378. // earlier attempt keeps its value) and mirrors ValidateUniqueIndex for a single
  1379. // plain column: NULLs do not collide. The caller holds the table's exclusive
  1380. // gate, so no writer can insert a conflicting row between this check and the
  1381. // publication of the index.
  1382. func (m *SchemaManager) validateAddColumnUnique(table string, column Column, index *Index) error {
  1383. seen := make(map[string]struct{})
  1384. return m.applyRows(table, func(row Row) (bool, error) {
  1385. value, ok := rowColumnValue(row, column.Name)
  1386. if !ok {
  1387. value = column.Default
  1388. }
  1389. if value == nil {
  1390. return false, nil
  1391. }
  1392. encoded := encodeUniqueScalar(value)
  1393. if _, duplicate := seen[encoded]; duplicate {
  1394. return false, &UniqueViolationError{Constraint: index.Name}
  1395. }
  1396. seen[encoded] = struct{}{}
  1397. return false, nil
  1398. })
  1399. }
  1400. // tableHasRows reports whether a table holds at least one durable row.
  1401. func (m *SchemaManager) tableHasRows(table string) (bool, error) {
  1402. prefix := []byte(fmt.Sprintf("%s:_data:%s:", m.database, strings.ToLower(table)))
  1403. found := false
  1404. err := m.pool.WithClient(func(client *KVClient) (retErr error) {
  1405. cursor, err := client.ScanWithLimit(prefix, 1)
  1406. if err != nil {
  1407. return err
  1408. }
  1409. defer func() {
  1410. if cerr := cursor.Close(); retErr == nil {
  1411. retErr = cerr
  1412. }
  1413. }()
  1414. entries, _, err := cursor.Next()
  1415. if err != nil {
  1416. return err
  1417. }
  1418. found = len(entries) > 0
  1419. return nil
  1420. })
  1421. return found, err
  1422. }
  1423. // getSchemaUnsafe gets a schema without locking (internal use).
  1424. func (m *SchemaManager) getSchemaUnsafe(table string) (*Schema, error) {
  1425. tableLower := strings.ToLower(table)
  1426. // Check cache
  1427. if schema, ok := m.cache[tableLower]; ok {
  1428. return schema, nil
  1429. }
  1430. // Read from storage
  1431. key := m.schemaKey(table)
  1432. var data string
  1433. err := m.pool.WithClient(func(c *KVClient) error {
  1434. var err error
  1435. data, err = c.Read(key)
  1436. return err
  1437. })
  1438. if err != nil {
  1439. return nil, fmt.Errorf("table not found: %s", table)
  1440. }
  1441. var schema Schema
  1442. if err := json.Unmarshal([]byte(data), &schema); err != nil {
  1443. return nil, err
  1444. }
  1445. m.cache[tableLower] = &schema
  1446. return &schema, nil
  1447. }
  1448. // updateSchemaUnsafe updates a schema without locking (internal use).
  1449. func (m *SchemaManager) updateSchemaUnsafe(schema *Schema) error {
  1450. key := m.schemaKey(schema.Name)
  1451. data, _ := json.Marshal(schema)
  1452. err := m.pool.WithClient(func(c *KVClient) error {
  1453. return c.Write(key, string(data))
  1454. })
  1455. if err != nil {
  1456. return err
  1457. }
  1458. // Update cache
  1459. m.cache[strings.ToLower(schema.Name)] = schema
  1460. m.bumpVersionLocked()
  1461. return nil
  1462. }