schema.go 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127
  1. package storage
  2. import (
  3. "errors"
  4. "fmt"
  5. "strconv"
  6. "strings"
  7. "sync"
  8. "time"
  9. "github.com/goccy/go-json"
  10. "github.com/danfragoso/pizzasql-next/pkg/analyzer"
  11. )
  12. // ErrIndexNotFound is returned by GetIndex when an index is absent. It is
  13. // distinct from a storage/IO error so callers like ListTableIndexes can skip a
  14. // concurrently-dropped index without swallowing real read failures.
  15. var ErrIndexNotFound = errors.New("index not found")
  16. // Schema represents a table schema.
  17. type Schema struct {
  18. Name string `json:"name"`
  19. Columns []Column `json:"columns"`
  20. // PrimaryKey is the single primary-key column. It stays the source of truth
  21. // for pre-existing catalogs that do not carry PrimaryKeyColumns, and it is
  22. // empty for a composite key so a caller cannot mistake one member for the
  23. // whole key. Use PrimaryKeyList instead of reading either field directly.
  24. PrimaryKey string `json:"primary_key"`
  25. // PrimaryKeyColumns is the ordered primary-key column list for a composite
  26. // key. It is omitted for single-column keys so the catalog keeps its
  27. // historical shape; normalizePrimaryKey fills it in when a schema is loaded.
  28. PrimaryKeyColumns []string `json:"primary_key_columns,omitempty"`
  29. CreatedAt time.Time `json:"created_at"`
  30. NextRowID int64 `json:"next_rowid"`
  31. AutoIncrement bool `json:"autoincrement"`
  32. // Checks holds the row predicates declared with CHECK, at column and table
  33. // level alike. Inline and table-level declarations are equivalent once
  34. // parsed, so both live in this one list.
  35. Checks []CheckConstraint `json:"checks,omitempty"`
  36. // ForeignKeys holds the FOREIGN KEY declarations. Each constraint is
  37. // enforced on every write and re-validated at transaction commit; a
  38. // cascading action rewrites or removes the referencing rows as part of the
  39. // same statement.
  40. ForeignKeys []ForeignKeyConstraint `json:"foreign_keys,omitempty"`
  41. }
  42. // ForeignKeyConstraint is a persisted FOREIGN KEY declaration. Columns are the
  43. // child columns in declaration order; RefColumns are the parent columns they are
  44. // matched against. Both sides have the same length, and the parent side is
  45. // validated at DDL to be the parent's PRIMARY KEY or a UNIQUE index.
  46. type ForeignKeyConstraint struct {
  47. Name string `json:"name,omitempty"`
  48. Columns []string `json:"columns"`
  49. RefTable string `json:"ref_table"`
  50. RefColumns []string `json:"ref_columns"`
  51. // OnDelete and OnUpdate hold the declared referential action text (NO
  52. // ACTION, RESTRICT, CASCADE, SET NULL, or SET DEFAULT). They are empty when
  53. // the clause was omitted and are kept so sqlite_master can reproduce the
  54. // declaration.
  55. OnDelete string `json:"on_delete,omitempty"`
  56. OnUpdate string `json:"on_update,omitempty"`
  57. }
  58. // Label identifies the constraint in error messages: the declared name when
  59. // there is one, otherwise the child column list.
  60. func (fk ForeignKeyConstraint) Label() string {
  61. if fk.Name != "" {
  62. return fk.Name
  63. }
  64. return strings.Join(fk.Columns, ", ") + " -> " + fk.RefTable
  65. }
  66. // CheckConstraint is a persisted CHECK predicate. The predicate is stored as
  67. // SQL text and re-parsed by the evaluator installed on the SchemaManager, so a
  68. // durable reload keeps enforcing it.
  69. type CheckConstraint struct {
  70. Name string `json:"name,omitempty"`
  71. Expression string `json:"expression"`
  72. }
  73. // Label identifies the constraint in error messages and the catalog: the
  74. // declared name when there is one, otherwise the expression text.
  75. func (c CheckConstraint) Label() string {
  76. if c.Name != "" {
  77. return c.Name
  78. }
  79. return c.Expression
  80. }
  81. // Column represents a column definition.
  82. type Column struct {
  83. Name string `json:"name"`
  84. Type string `json:"type"`
  85. Nullable bool `json:"nullable"`
  86. // Default holds the evaluated constant DEFAULT. DefaultExpr holds the SQL
  87. // text of a non-constant DEFAULT (CURRENT_TIMESTAMP and the other
  88. // clock-reading forms) so it is evaluated on every write instead of being
  89. // frozen at DDL time. Only one of the two is set; DefaultExpr takes
  90. // precedence if a hand-edited catalog sets both.
  91. Default interface{} `json:"default,omitempty"`
  92. DefaultExpr string `json:"default_expr,omitempty"`
  93. PrimaryKey bool `json:"primary_key"`
  94. // GeneratedExpr holds the SQL text of a GENERATED ALWAYS AS (expr) column.
  95. // GeneratedStored reports whether the value is materialized on write
  96. // (STORED, the only form this engine persists) versus computed on read.
  97. GeneratedExpr string `json:"generated_expr,omitempty"`
  98. GeneratedStored bool `json:"generated_stored,omitempty"`
  99. }
  100. // DefaultLiteral returns the catalog representation of the column's default:
  101. // the evaluated constant value, or the SQL text of a non-constant default.
  102. // DefaultExpr takes precedence when a hand-edited catalog sets both.
  103. func (c Column) DefaultLiteral() interface{} {
  104. if c.DefaultExpr != "" {
  105. return c.DefaultExpr
  106. }
  107. if c.Default != nil {
  108. return c.Default
  109. }
  110. return nil
  111. }
  112. // Index represents an index definition.
  113. type Index struct {
  114. Name string `json:"name"`
  115. Table string `json:"table"`
  116. Columns []IndexColumn `json:"columns"`
  117. Unique bool `json:"unique"`
  118. CreatedAt time.Time `json:"created_at"`
  119. // OnConflict is the default conflict resolution declared for this index via
  120. // a UNIQUE(...) ON CONFLICT clause. Empty means the SQLite default (ABORT).
  121. OnConflict string `json:"on_conflict,omitempty"`
  122. }
  123. // IndexColumn represents a column in an index. Expression is set for expression
  124. // indexes (e.g. lower(email)); a plain column index leaves it empty and uses
  125. // Name.
  126. type IndexColumn struct {
  127. Name string `json:"name"`
  128. Desc bool `json:"desc"`
  129. Expression string `json:"expression,omitempty"`
  130. }
  131. // rowIDAllocator owns the next-ROWID state for a single table. It is a separate
  132. // mutex per table so allocating a ROWID on one table never serializes against
  133. // another table, and never contends with the SchemaManager catalog lock.
  134. type rowIDAllocator struct {
  135. mu sync.Mutex
  136. next int64
  137. init bool
  138. }
  139. // SchemaManager manages table schemas.
  140. type SchemaManager struct {
  141. pool *KVPool
  142. database string
  143. cache map[string]*Schema
  144. indexCache map[string]*Index
  145. indexListCache []string
  146. indexListCached bool
  147. version uint64
  148. mu sync.RWMutex
  149. tableLocksMu sync.Mutex
  150. tableLocks map[string]*sync.RWMutex
  151. // checkMu guards checkEval, the pluggable evaluator for persisted CHECK
  152. // predicates. It is set by the SQL executor so storage stays independent of
  153. // the SQL front end.
  154. checkMu sync.RWMutex
  155. checkEval CheckEvaluator
  156. rowIDMu sync.Mutex
  157. rowIDAlloc map[string]*rowIDAllocator
  158. // defaultEval evaluates a persisted non-constant DEFAULT expression. The
  159. // SQL executor registers one so storage can backfill ADD COLUMN rows and
  160. // complete row images without importing the parser or executor.
  161. // defaultClock supplies the instant a DDL statement samples once for every
  162. // expression default it touches.
  163. defaultEvalMu sync.RWMutex
  164. defaultEval DefaultEvaluator
  165. defaultClock DefaultClock
  166. // fkCatalogMu guards fkCatalog, the cached foreign-key metadata used to find
  167. // referencing tables without re-reading every schema on every write.
  168. fkCatalogMu sync.Mutex
  169. fkCatalog *foreignKeyCatalog
  170. }
  171. // DefaultEvaluator evaluates a persisted non-constant DEFAULT expression, such
  172. // as CURRENT_TIMESTAMP, at the supplied instant. Expression defaults are never
  173. // frozen at DDL time; the caller samples one instant per statement so every row
  174. // it touches sees the same value.
  175. type DefaultEvaluator func(expression string, now time.Time) (interface{}, error)
  176. // DefaultClock supplies the instant a statement's expression defaults use. The
  177. // SQL executor registers a clock backed by the session so a storage-side ADD
  178. // COLUMN backfill matches statement-time now().
  179. type DefaultClock func() time.Time
  180. // SetDefaultEvaluator installs the evaluator used for expression defaults.
  181. func (m *SchemaManager) SetDefaultEvaluator(eval DefaultEvaluator) {
  182. m.defaultEvalMu.Lock()
  183. m.defaultEval = eval
  184. m.defaultEvalMu.Unlock()
  185. }
  186. // SetDefaultClock installs the clock sampled once per DDL statement for
  187. // expression defaults.
  188. func (m *SchemaManager) SetDefaultClock(clock DefaultClock) {
  189. m.defaultEvalMu.Lock()
  190. m.defaultClock = clock
  191. m.defaultEvalMu.Unlock()
  192. }
  193. func (m *SchemaManager) defaultEvaluator() DefaultEvaluator {
  194. m.defaultEvalMu.RLock()
  195. defer m.defaultEvalMu.RUnlock()
  196. return m.defaultEval
  197. }
  198. // defaultNow samples the registered clock, falling back to the wall clock.
  199. // Callers sample it once per statement and pass the instant down so validation
  200. // and the rewrite observe the same value.
  201. func (m *SchemaManager) defaultNow() time.Time {
  202. m.defaultEvalMu.RLock()
  203. clock := m.defaultClock
  204. m.defaultEvalMu.RUnlock()
  205. if clock != nil {
  206. return clock().UTC()
  207. }
  208. return time.Now().UTC()
  209. }
  210. // CheckEvaluator reports whether a persisted CHECK expression holds for a row.
  211. // A false result is a violation; NULL and other unknown results must be
  212. // reported as true, matching SQL three-valued logic. The SQL executor registers
  213. // one so the storage layer can enforce CHECK without importing the parser.
  214. type CheckEvaluator func(expression string, row Row) (bool, error)
  215. // SetCheckEvaluator installs the evaluator used to enforce persisted CHECK
  216. // predicates.
  217. func (m *SchemaManager) SetCheckEvaluator(eval CheckEvaluator) {
  218. m.checkMu.Lock()
  219. m.checkEval = eval
  220. m.checkMu.Unlock()
  221. }
  222. func (m *SchemaManager) checkEvaluator() CheckEvaluator {
  223. m.checkMu.RLock()
  224. defer m.checkMu.RUnlock()
  225. return m.checkEval
  226. }
  227. // BeginTransaction is retained for API compatibility. Buffered per-session
  228. // transactions no longer take a database-wide transaction lock; staged writes
  229. // are validated and committed atomically with CompareBatchWrite instead.
  230. func (m *SchemaManager) BeginTransaction() {}
  231. // EndTransaction is retained for API compatibility.
  232. func (m *SchemaManager) EndTransaction() {}
  233. // LockStatement is retained for API compatibility. Statement execution is now
  234. // serialized through per-table locks and optimistic validation, so no global
  235. // statement lock is required.
  236. func (m *SchemaManager) LockStatement() {}
  237. // UnlockStatement is retained for API compatibility.
  238. func (m *SchemaManager) UnlockStatement() {}
  239. // NewSchemaManager creates a new schema manager.
  240. func NewSchemaManager(pool *KVPool, database string) *SchemaManager {
  241. return &SchemaManager{
  242. pool: pool,
  243. database: database,
  244. cache: make(map[string]*Schema),
  245. indexCache: make(map[string]*Index),
  246. tableLocks: make(map[string]*sync.RWMutex),
  247. rowIDAlloc: make(map[string]*rowIDAllocator),
  248. }
  249. }
  250. // rowIDAllocatorFor returns (creating if needed) the per-table ROWID allocator.
  251. func (m *SchemaManager) rowIDAllocatorFor(table string) *rowIDAllocator {
  252. key := strings.ToLower(table)
  253. m.rowIDMu.Lock()
  254. a, ok := m.rowIDAlloc[key]
  255. if !ok {
  256. a = &rowIDAllocator{}
  257. m.rowIDAlloc[key] = a
  258. }
  259. m.rowIDMu.Unlock()
  260. return a
  261. }
  262. func (m *SchemaManager) tableLock(table string) *sync.RWMutex {
  263. key := strings.ToLower(table)
  264. m.tableLocksMu.Lock()
  265. lock, ok := m.tableLocks[key]
  266. if !ok {
  267. lock = &sync.RWMutex{}
  268. m.tableLocks[key] = lock
  269. }
  270. m.tableLocksMu.Unlock()
  271. return lock
  272. }
  273. // GetDatabaseName returns the database name.
  274. func (m *SchemaManager) GetDatabaseName() string {
  275. return m.database
  276. }
  277. // GetPool returns the KV pool.
  278. func (m *SchemaManager) GetPool() *KVPool {
  279. return m.pool
  280. }
  281. // Version returns the in-process schema catalog version. It is incremented for
  282. // schema/index definition changes so cached executors can resync their analyzer
  283. // catalogs without scanning storage on every query.
  284. func (m *SchemaManager) Version() uint64 {
  285. m.mu.RLock()
  286. defer m.mu.RUnlock()
  287. return m.version
  288. }
  289. func (m *SchemaManager) bumpVersionLocked() {
  290. m.version++
  291. }
  292. // schemaKey returns the key for a table schema.
  293. func (m *SchemaManager) schemaKey(table string) string {
  294. return fmt.Sprintf("%s:_schema:%s", m.database, strings.ToLower(table))
  295. }
  296. // catalogKey returns the key for the table catalog.
  297. func (m *SchemaManager) catalogKey() string {
  298. return fmt.Sprintf("%s:_sys:tables", m.database)
  299. }
  300. // rowIDKey returns the key for a table's next ROWID counter.
  301. func (m *SchemaManager) rowIDKey(table string) string {
  302. return fmt.Sprintf("%s:_sys:rowid:%s", m.database, strings.ToLower(table))
  303. }
  304. // readDurable reads a catalog key straight from durable storage, bypassing the
  305. // in-memory caches, and reports the LSN the store observed it at. Transactional
  306. // DDL uses it so a staged catalog change is pinned to the exact durable version
  307. // it was derived from, and a concurrent committed DDL fails the commit instead
  308. // of being silently overwritten.
  309. func (m *SchemaManager) readDurable(key string) (value string, lsn uint64, found bool, err error) {
  310. err = m.pool.WithClient(func(c *KVClient) error {
  311. var rerr error
  312. value, lsn, found, rerr = c.ReadWithLSN(key)
  313. return rerr
  314. })
  315. return value, lsn, found, err
  316. }
  317. // catalogTablesDurable returns the committed table catalog and its LSN.
  318. func (m *SchemaManager) catalogTablesDurable() ([]string, uint64, error) {
  319. data, lsn, found, err := m.readDurable(m.catalogKey())
  320. if err != nil {
  321. return nil, 0, err
  322. }
  323. if !found {
  324. return nil, lsn, nil
  325. }
  326. var tables []string
  327. if err := json.Unmarshal([]byte(data), &tables); err != nil {
  328. return nil, 0, fmt.Errorf("failed to parse catalog: %w", err)
  329. }
  330. return tables, lsn, nil
  331. }
  332. // indexListDurable returns the committed index catalog and its LSN.
  333. func (m *SchemaManager) indexListDurable() ([]string, uint64, error) {
  334. data, lsn, found, err := m.readDurable(m.indexListKey())
  335. if err != nil {
  336. return nil, 0, err
  337. }
  338. if !found {
  339. return nil, lsn, nil
  340. }
  341. var indexes []string
  342. if err := json.Unmarshal([]byte(data), &indexes); err != nil {
  343. return nil, 0, fmt.Errorf("failed to parse index list: %w", err)
  344. }
  345. return indexes, lsn, nil
  346. }
  347. // invalidateCommittedDDL publishes a committed transactional DDL change to
  348. // readers: every cache derived from the catalog is dropped and the version is
  349. // bumped so the foreign-key metadata and session analyzers reload. The caches
  350. // are rebuilt lazily from the durable catalog, which the commit already wrote.
  351. //
  352. // Only the touched tables lose their ROWID allocator. Wiping every allocator
  353. // would let a concurrent transaction that staged a TEXT/composite-key insert
  354. // (whose ROWID is not durable yet) derive the same ROWID again and publish a
  355. // duplicate, so untouched tables keep their derived counters.
  356. func (m *SchemaManager) invalidateCommittedDDL(tables []string) {
  357. m.mu.Lock()
  358. defer m.mu.Unlock()
  359. m.cache = make(map[string]*Schema)
  360. m.indexCache = make(map[string]*Index)
  361. m.indexListCache = nil
  362. m.indexListCached = false
  363. m.rowIDMu.Lock()
  364. for _, table := range tables {
  365. delete(m.rowIDAlloc, strings.ToLower(table))
  366. }
  367. m.rowIDMu.Unlock()
  368. m.fkCatalogMu.Lock()
  369. m.fkCatalog = nil
  370. m.fkCatalogMu.Unlock()
  371. m.bumpVersionLocked()
  372. }
  373. // CreateTable creates a new table.
  374. func (m *SchemaManager) CreateTable(schema *Schema) error {
  375. m.mu.Lock()
  376. defer m.mu.Unlock()
  377. // Check if table already exists
  378. key := m.schemaKey(schema.Name)
  379. err := m.pool.WithClient(func(c *KVClient) error {
  380. _, err := c.Read(key)
  381. return err
  382. })
  383. if err == nil {
  384. return fmt.Errorf("table already exists: %s", schema.Name)
  385. }
  386. // Keep the cached schema private so callers cannot mutate a published
  387. // catalog snapshot after this operation returns.
  388. schema = cloneSchema(schema)
  389. schema.CreatedAt = time.Now()
  390. // Determine the primary key if not set. A schema with no declared key uses
  391. // the synthetic _rowid_ so user columns remain unconstrained and can hold
  392. // duplicate or NULL values.
  393. schema.normalizePrimaryKey()
  394. // Serialize schema
  395. data, err := json.Marshal(schema)
  396. if err != nil {
  397. return fmt.Errorf("failed to serialize schema: %w", err)
  398. }
  399. // Write schema
  400. err = m.pool.WithClient(func(c *KVClient) error {
  401. return c.Write(key, string(data))
  402. })
  403. if err != nil {
  404. return fmt.Errorf("failed to write schema: %w", err)
  405. }
  406. // Update catalog
  407. if err := m.addToCatalog(schema.Name); err != nil {
  408. // Rollback schema write
  409. m.pool.WithClient(func(c *KVClient) error {
  410. return c.Delete(key)
  411. })
  412. return err
  413. }
  414. // Update cache
  415. m.cache[strings.ToLower(schema.Name)] = schema
  416. m.bumpVersionLocked()
  417. return nil
  418. }
  419. // DropTable drops a table.
  420. func (m *SchemaManager) DropTable(name string) error {
  421. tableLock := m.tableLock(name)
  422. tableLock.Lock()
  423. defer tableLock.Unlock()
  424. m.mu.Lock()
  425. defer m.mu.Unlock()
  426. key := m.schemaKey(name)
  427. // Check if table exists
  428. err := m.pool.WithClient(func(c *KVClient) error {
  429. _, err := c.Read(key)
  430. return err
  431. })
  432. if err != nil {
  433. return fmt.Errorf("table not found: %s", name)
  434. }
  435. // Delete all rows by scanning their actual keys and batch-deleting them, so
  436. // a table drop no longer leaks durable rows.
  437. if err := m.deleteKeysWithPrefix([]byte(fmt.Sprintf("%s:_data:%s:", m.database, strings.ToLower(name)))); err != nil {
  438. return err
  439. }
  440. // Delete schema
  441. err = m.pool.WithClient(func(c *KVClient) error {
  442. return c.Delete(key)
  443. })
  444. if err != nil {
  445. return fmt.Errorf("failed to delete schema: %w", err)
  446. }
  447. // Delete ROWID state.
  448. m.pool.WithClient(func(c *KVClient) error {
  449. return c.Delete(m.rowIDKey(name))
  450. })
  451. // Update catalog
  452. if err := m.removeFromCatalog(name); err != nil {
  453. return err
  454. }
  455. // Update cache
  456. tableLower := strings.ToLower(name)
  457. delete(m.cache, tableLower)
  458. m.rowIDMu.Lock()
  459. delete(m.rowIDAlloc, tableLower)
  460. m.rowIDMu.Unlock()
  461. m.bumpVersionLocked()
  462. return nil
  463. }
  464. // GetSchema retrieves a table schema.
  465. func (m *SchemaManager) GetSchema(name string) (*Schema, error) {
  466. m.mu.RLock()
  467. if schema, ok := m.cache[strings.ToLower(name)]; ok {
  468. // Clone while still holding the read lock: the cached schema's
  469. // NextRowID field is mutated under the write lock, so cloning outside
  470. // the lock races with that mutation.
  471. cloned := cloneSchema(schema)
  472. m.mu.RUnlock()
  473. return cloned, nil
  474. }
  475. m.mu.RUnlock()
  476. m.mu.Lock()
  477. defer m.mu.Unlock()
  478. // Double-check after acquiring write lock
  479. if schema, ok := m.cache[strings.ToLower(name)]; ok {
  480. return cloneSchema(schema), nil
  481. }
  482. key := m.schemaKey(name)
  483. var data string
  484. err := m.pool.WithClient(func(c *KVClient) error {
  485. var err error
  486. data, err = c.Read(key)
  487. return err
  488. })
  489. if err != nil {
  490. if err == ErrKeyNotFound {
  491. return nil, fmt.Errorf("table not found: %s", name)
  492. }
  493. return nil, err
  494. }
  495. var schema Schema
  496. if err := json.Unmarshal([]byte(data), &schema); err != nil {
  497. return nil, fmt.Errorf("failed to parse schema: %w", err)
  498. }
  499. schema.normalizePrimaryKey()
  500. m.cache[strings.ToLower(name)] = &schema
  501. return cloneSchema(&schema), nil
  502. }
  503. func cloneSchema(schema *Schema) *Schema {
  504. if schema == nil {
  505. return nil
  506. }
  507. cloned := *schema
  508. cloned.Columns = append([]Column(nil), schema.Columns...)
  509. cloned.Checks = append([]CheckConstraint(nil), schema.Checks...)
  510. cloned.PrimaryKeyColumns = append([]string(nil), schema.PrimaryKeyColumns...)
  511. if schema.ForeignKeys != nil {
  512. cloned.ForeignKeys = make([]ForeignKeyConstraint, len(schema.ForeignKeys))
  513. for i, fk := range schema.ForeignKeys {
  514. cloned.ForeignKeys[i] = ForeignKeyConstraint{
  515. Name: fk.Name,
  516. Columns: append([]string(nil), fk.Columns...),
  517. RefTable: fk.RefTable,
  518. RefColumns: append([]string(nil), fk.RefColumns...),
  519. OnDelete: fk.OnDelete,
  520. OnUpdate: fk.OnUpdate,
  521. }
  522. }
  523. }
  524. return &cloned
  525. }
  526. func cloneIndex(index *Index) *Index {
  527. if index == nil {
  528. return nil
  529. }
  530. cloned := *index
  531. cloned.Columns = append([]IndexColumn(nil), index.Columns...)
  532. return &cloned
  533. }
  534. // TableExists checks if a table exists.
  535. func (m *SchemaManager) TableExists(name string) bool {
  536. _, err := m.GetSchema(name)
  537. return err == nil
  538. }
  539. // ListTables returns all table names.
  540. func (m *SchemaManager) ListTables() ([]string, error) {
  541. var data string
  542. err := m.pool.WithClient(func(c *KVClient) error {
  543. var err error
  544. data, err = c.Read(m.catalogKey())
  545. return err
  546. })
  547. if err != nil {
  548. if err == ErrKeyNotFound {
  549. return nil, nil
  550. }
  551. return nil, err
  552. }
  553. var tables []string
  554. if err := json.Unmarshal([]byte(data), &tables); err != nil {
  555. return nil, fmt.Errorf("failed to parse catalog: %w", err)
  556. }
  557. return tables, nil
  558. }
  559. // addToCatalog adds a table to the catalog.
  560. func (m *SchemaManager) addToCatalog(name string) error {
  561. tables, err := m.ListTables()
  562. if err != nil && err != ErrKeyNotFound {
  563. return err
  564. }
  565. // Check if already exists
  566. lowerName := strings.ToLower(name)
  567. for _, t := range tables {
  568. if strings.ToLower(t) == lowerName {
  569. return nil
  570. }
  571. }
  572. tables = append(tables, name)
  573. data, err := json.Marshal(tables)
  574. if err != nil {
  575. return err
  576. }
  577. return m.pool.WithClient(func(c *KVClient) error {
  578. return c.Write(m.catalogKey(), string(data))
  579. })
  580. }
  581. // removeFromCatalog removes a table from the catalog.
  582. func (m *SchemaManager) removeFromCatalog(name string) error {
  583. tables, err := m.ListTables()
  584. if err != nil {
  585. return err
  586. }
  587. lowerName := strings.ToLower(name)
  588. newTables := make([]string, 0, len(tables))
  589. for _, t := range tables {
  590. if strings.ToLower(t) != lowerName {
  591. newTables = append(newTables, t)
  592. }
  593. }
  594. data, err := json.Marshal(newTables)
  595. if err != nil {
  596. return err
  597. }
  598. return m.pool.WithClient(func(c *KVClient) error {
  599. return c.Write(m.catalogKey(), string(data))
  600. })
  601. }
  602. // InvalidateCache clears the cache for a table.
  603. func (m *SchemaManager) InvalidateCache(name string) {
  604. m.mu.Lock()
  605. defer m.mu.Unlock()
  606. tableLower := strings.ToLower(name)
  607. delete(m.cache, tableLower)
  608. m.rowIDMu.Lock()
  609. delete(m.rowIDAlloc, tableLower)
  610. m.rowIDMu.Unlock()
  611. }
  612. // ToAnalyzerTableInfo converts a Schema to analyzer.TableInfo.
  613. func (s *Schema) ToAnalyzerTableInfo() *analyzer.TableInfo {
  614. info := &analyzer.TableInfo{
  615. Name: s.Name,
  616. }
  617. for _, col := range s.Columns {
  618. info.Columns = append(info.Columns, analyzer.ColumnInfo{
  619. Name: col.Name,
  620. Type: analyzer.TypeFromName(col.Type),
  621. Nullable: col.Nullable,
  622. PrimaryKey: col.PrimaryKey,
  623. TableName: s.Name,
  624. Generated: col.GeneratedExpr != "",
  625. Array: strings.HasSuffix(strings.ToUpper(strings.TrimSpace(col.Type)), "[]"),
  626. })
  627. }
  628. return info
  629. }
  630. // normalizePrimaryKey derives the ordered primary-key column list from the
  631. // legacy single-column field or from the columns marked PRIMARY KEY, and keeps
  632. // both representations consistent. Primary-key columns are implicitly NOT NULL.
  633. func (s *Schema) normalizePrimaryKey() {
  634. if len(s.PrimaryKeyColumns) == 0 {
  635. if s.PrimaryKey != "" {
  636. s.PrimaryKeyColumns = []string{s.PrimaryKey}
  637. } else {
  638. for _, col := range s.Columns {
  639. if col.PrimaryKey {
  640. s.PrimaryKeyColumns = append(s.PrimaryKeyColumns, col.Name)
  641. }
  642. }
  643. if len(s.PrimaryKeyColumns) == 0 {
  644. s.PrimaryKeyColumns = []string{"_rowid_"}
  645. }
  646. }
  647. }
  648. if len(s.PrimaryKeyColumns) == 1 {
  649. // A single-column key keeps the historical catalog shape: only the
  650. // scalar field, so existing schema bytes stay unchanged.
  651. s.PrimaryKey = s.PrimaryKeyColumns[0]
  652. s.PrimaryKeyColumns = nil
  653. } else {
  654. s.PrimaryKey = ""
  655. }
  656. for i := range s.Columns {
  657. if s.IsPrimaryKeyColumn(s.Columns[i].Name) {
  658. s.Columns[i].PrimaryKey = true
  659. s.Columns[i].Nullable = false
  660. }
  661. }
  662. }
  663. // PrimaryKeyList returns the ordered primary-key columns. A schema always has
  664. // at least one: an explicit key, or the synthetic _rowid_.
  665. func (s *Schema) PrimaryKeyList() []string {
  666. if len(s.PrimaryKeyColumns) > 0 {
  667. return append([]string(nil), s.PrimaryKeyColumns...)
  668. }
  669. if s.PrimaryKey != "" {
  670. return []string{s.PrimaryKey}
  671. }
  672. return []string{"_rowid_"}
  673. }
  674. // UsesSyntheticRowID reports whether the table declares no primary key, so rows
  675. // are stored under the engine-assigned ROWID.
  676. func (s *Schema) UsesSyntheticRowID() bool {
  677. columns := s.PrimaryKeyList()
  678. return len(columns) == 1 && strings.EqualFold(columns[0], "_rowid_")
  679. }
  680. // IsCompositePrimaryKey reports whether the primary key spans more than one
  681. // column.
  682. func (s *Schema) IsCompositePrimaryKey() bool {
  683. return len(s.PrimaryKeyList()) > 1
  684. }
  685. // IsSingleColumnPrimaryKey reports whether the primary key is exactly one
  686. // column, which is the only shape a durable point lookup may address with one
  687. // value.
  688. func (s *Schema) IsSingleColumnPrimaryKey() bool {
  689. return len(s.PrimaryKeyList()) == 1
  690. }
  691. // IsPrimaryKeyColumn reports whether name is one of the primary-key columns.
  692. func (s *Schema) IsPrimaryKeyColumn(name string) bool {
  693. for _, column := range s.PrimaryKeyList() {
  694. if strings.EqualFold(column, name) {
  695. return true
  696. }
  697. }
  698. return false
  699. }
  700. // PrimaryKeyTargetMatches reports whether columns names the complete
  701. // primary-key column set. Order is not significant: ON CONFLICT (b, a) on a
  702. // PRIMARY KEY (a, b) addresses the same key, because the encoded key is built
  703. // in declaration order either way. SQLite instead requires the declaration
  704. // order of a constraint; this engine already accepts arbitrary conflict-target
  705. // lists, so it matches the set rather than raising.
  706. func (s *Schema) PrimaryKeyTargetMatches(columns []string) bool {
  707. primary := s.PrimaryKeyList()
  708. if len(primary) != len(columns) {
  709. return false
  710. }
  711. for _, column := range primary {
  712. found := false
  713. for _, candidate := range columns {
  714. if strings.EqualFold(column, candidate) {
  715. found = true
  716. break
  717. }
  718. }
  719. if !found {
  720. return false
  721. }
  722. }
  723. return true
  724. }
  725. // PrimaryKeyForRow returns the row's primary key encoded the way the table's
  726. // durable row keys encode it. A single-column key keeps the historical
  727. // "<value>" form, so existing databases are read and written unchanged. A
  728. // composite key length-prefixes each component ("<len>:<value>" repeated), a
  729. // prefix-free encoding, so ("ab","c") and ("a","bc") cannot collide. A NULL or
  730. // missing component is a NOT NULL violation: no rowid is auto-assigned.
  731. func (s *Schema) PrimaryKeyForRow(row Row) (string, error) {
  732. columns := s.PrimaryKeyList()
  733. parts := make([]string, len(columns))
  734. for i, column := range columns {
  735. value, ok := rowColumnValue(row, column)
  736. if !ok || value == nil {
  737. return "", &NotNullViolationError{Table: s.Name, Column: column}
  738. }
  739. parts[i] = fmt.Sprintf("%v", value)
  740. }
  741. if len(parts) == 1 {
  742. return parts[0], nil
  743. }
  744. var b strings.Builder
  745. for _, part := range parts {
  746. b.WriteString(strconv.Itoa(len(part)))
  747. b.WriteByte(':')
  748. b.WriteString(part)
  749. }
  750. return b.String(), nil
  751. }
  752. // GetColumn returns a column by name.
  753. func (s *Schema) GetColumn(name string) (*Column, bool) {
  754. lowerName := strings.ToLower(name)
  755. for i := range s.Columns {
  756. if strings.ToLower(s.Columns[i].Name) == lowerName {
  757. return &s.Columns[i], true
  758. }
  759. }
  760. return nil, false
  761. }
  762. // GetNextRowID gets and increments the next ROWID for a table. Allocation is
  763. // serialized per table via the table's own allocator so inserts on different
  764. // tables never contend, and no global SchemaManager lock is held across the
  765. // durable derivation scan.
  766. func (m *SchemaManager) GetNextRowID(table string) (int64, error) {
  767. alloc := m.rowIDAllocatorFor(table)
  768. alloc.mu.Lock()
  769. defer alloc.mu.Unlock()
  770. next, err := m.nextRowIDLocked(alloc, table)
  771. if err != nil {
  772. return 0, err
  773. }
  774. alloc.next = next + 1
  775. return next, nil
  776. }
  777. // UpdateMaxRowID updates the next ROWID if the provided value is higher.
  778. func (m *SchemaManager) UpdateMaxRowID(table string, rowid int64) error {
  779. alloc := m.rowIDAllocatorFor(table)
  780. alloc.mu.Lock()
  781. defer alloc.mu.Unlock()
  782. next, err := m.nextRowIDLocked(alloc, table)
  783. if err != nil {
  784. return err
  785. }
  786. if rowid >= next {
  787. alloc.next = rowid + 1
  788. }
  789. return nil
  790. }
  791. // nextRowIDLocked returns the current next ROWID, deriving it from durable rows
  792. // on first use (must hold the per-table allocator lock).
  793. func (m *SchemaManager) nextRowIDLocked(alloc *rowIDAllocator, table string) (int64, error) {
  794. if alloc.init {
  795. return alloc.next, nil
  796. }
  797. next, err := m.deriveNextRowID(table)
  798. if err != nil {
  799. return 0, err
  800. }
  801. if next < 1 {
  802. next = 1
  803. }
  804. alloc.next = next
  805. alloc.init = true
  806. return alloc.next, nil
  807. }
  808. // deriveNextRowID scans durable row keys to recover max(rowid)+1, streaming
  809. // each page through decodeRow instead of materializing every value.
  810. func (m *SchemaManager) deriveNextRowID(table string) (int64, error) {
  811. prefix := []byte(fmt.Sprintf("%s:_data:%s:", m.database, strings.ToLower(table)))
  812. var maxRowID int64
  813. err := m.pool.WithClient(func(client *KVClient) (retErr error) {
  814. cursor, err := client.Scan(prefix)
  815. if err != nil {
  816. return err
  817. }
  818. defer func() {
  819. if err := cursor.Close(); retErr == nil {
  820. retErr = err
  821. }
  822. }()
  823. for {
  824. entries, done, err := cursor.Next()
  825. if err != nil {
  826. return err
  827. }
  828. for _, e := range entries {
  829. row, err := decodeRow(e.Value)
  830. if err != nil {
  831. return fmt.Errorf("failed to parse row while deriving ROWID: %w", err)
  832. }
  833. if rowid, ok := valueAsInt64(row["_rowid_"]); ok && rowid > maxRowID {
  834. maxRowID = rowid
  835. }
  836. }
  837. if done {
  838. return nil
  839. }
  840. }
  841. })
  842. if err != nil {
  843. return 0, err
  844. }
  845. return maxRowID + 1, nil
  846. }
  847. // deleteKeysWithPrefix streams the keys with the given prefix one page at a
  848. // time and atomically batch-deletes them, so a bulk operation never leaves
  849. // durable rows behind.
  850. func (m *SchemaManager) deleteKeysWithPrefix(prefix []byte) error {
  851. return m.pool.WithClient(func(client *KVClient) (retErr error) {
  852. cursor, err := client.ScanKeys(prefix)
  853. if err != nil {
  854. return err
  855. }
  856. defer func() {
  857. if err := cursor.Close(); retErr == nil {
  858. retErr = err
  859. }
  860. }()
  861. ops := make([]BatchOp, 0, scanPageSize)
  862. batchBytes := 8
  863. flush := func() error {
  864. if len(ops) == 0 {
  865. return nil
  866. }
  867. if _, err := client.BatchWrite(ops, nil); err != nil {
  868. return err
  869. }
  870. ops = ops[:0]
  871. batchBytes = 8
  872. return nil
  873. }
  874. for {
  875. entries, done, err := cursor.Next()
  876. if err != nil {
  877. return err
  878. }
  879. for _, e := range entries {
  880. opBytes := 12 + len(e.Key)
  881. if len(ops) == maxOperations || batchBytes+opBytes > bulkBatchByteBudget {
  882. if err := flush(); err != nil {
  883. return err
  884. }
  885. }
  886. ops = append(ops, BatchOp{Op: batchDelete, Key: append([]byte(nil), e.Key...)})
  887. batchBytes += opBytes
  888. }
  889. if done {
  890. return flush()
  891. }
  892. }
  893. })
  894. }
  895. func valueAsInt64(value interface{}) (int64, bool) {
  896. switch v := value.(type) {
  897. case int64:
  898. return v, true
  899. case int:
  900. return int64(v), true
  901. case float64:
  902. return int64(v), true
  903. default:
  904. return 0, false
  905. }
  906. }
  907. // getSchemaLocked retrieves schema (must hold lock).
  908. func (m *SchemaManager) getSchemaLocked(name string) (*Schema, error) {
  909. if schema, ok := m.cache[strings.ToLower(name)]; ok {
  910. return schema, nil
  911. }
  912. key := m.schemaKey(name)
  913. var data string
  914. err := m.pool.WithClient(func(c *KVClient) error {
  915. var err error
  916. data, err = c.Read(key)
  917. return err
  918. })
  919. if err != nil {
  920. if err == ErrKeyNotFound {
  921. return nil, fmt.Errorf("table not found: %s", name)
  922. }
  923. return nil, err
  924. }
  925. var schema Schema
  926. if err := json.Unmarshal([]byte(data), &schema); err != nil {
  927. return nil, fmt.Errorf("failed to parse schema: %w", err)
  928. }
  929. schema.normalizePrimaryKey()
  930. m.cache[strings.ToLower(name)] = &schema
  931. return &schema, nil
  932. }
  933. // saveSchemaLocked saves schema (must hold lock).
  934. func (m *SchemaManager) saveSchemaLocked(schema *Schema) error {
  935. data, err := json.Marshal(schema)
  936. if err != nil {
  937. return fmt.Errorf("failed to serialize schema: %w", err)
  938. }
  939. key := m.schemaKey(schema.Name)
  940. err = m.pool.WithClient(func(c *KVClient) error {
  941. return c.Write(key, string(data))
  942. })
  943. if err != nil {
  944. return fmt.Errorf("failed to write schema: %w", err)
  945. }
  946. m.cache[strings.ToLower(schema.Name)] = schema
  947. return nil
  948. }
  949. // Index management methods
  950. // indexKey returns the key for an index.
  951. func (m *SchemaManager) indexKey(name string) string {
  952. return fmt.Sprintf("%s:index:%s", m.database, strings.ToLower(name))
  953. }
  954. // indexListKey returns the key for the index list.
  955. func (m *SchemaManager) indexListKey() string {
  956. return fmt.Sprintf("%s:indexes", m.database)
  957. }
  958. // CreateIndex creates a new index.
  959. func (m *SchemaManager) CreateIndex(index *Index) error {
  960. m.mu.Lock()
  961. defer m.mu.Unlock()
  962. // Check if index already exists
  963. key := m.indexKey(index.Name)
  964. err := m.pool.WithClient(func(c *KVClient) error {
  965. _, err := c.Read(key)
  966. return err
  967. })
  968. if err == nil {
  969. return fmt.Errorf("index already exists: %s", index.Name)
  970. }
  971. // Verify table exists
  972. if _, err := m.getSchemaLocked(index.Table); err != nil {
  973. return fmt.Errorf("table not found: %s", index.Table)
  974. }
  975. // Save index
  976. index.CreatedAt = time.Now()
  977. data, err := json.Marshal(index)
  978. if err != nil {
  979. return fmt.Errorf("failed to serialize index: %w", err)
  980. }
  981. err = m.pool.WithClient(func(c *KVClient) error {
  982. return c.Write(key, string(data))
  983. })
  984. if err != nil {
  985. return fmt.Errorf("failed to write index: %w", err)
  986. }
  987. // Add to index list
  988. if err := m.addToIndexList(index.Name); err != nil {
  989. return err
  990. }
  991. m.indexCache[strings.ToLower(index.Name)] = cloneIndex(index)
  992. m.bumpVersionLocked()
  993. return nil
  994. }
  995. // DropIndex drops an index.
  996. func (m *SchemaManager) DropIndex(name string) error {
  997. m.mu.Lock()
  998. defer m.mu.Unlock()
  999. key := m.indexKey(name)
  1000. err := m.pool.WithClient(func(c *KVClient) error {
  1001. return c.Delete(key)
  1002. })
  1003. if err != nil {
  1004. return fmt.Errorf("failed to delete index: %w", err)
  1005. }
  1006. if err := m.removeFromIndexList(name); err != nil {
  1007. return err
  1008. }
  1009. delete(m.indexCache, strings.ToLower(name))
  1010. m.bumpVersionLocked()
  1011. return nil
  1012. }
  1013. // IndexExists checks if an index exists.
  1014. func (m *SchemaManager) IndexExists(name string) bool {
  1015. m.mu.RLock()
  1016. defer m.mu.RUnlock()
  1017. return m.indexExistsUnsafe(name)
  1018. }
  1019. // indexExistsUnsafe reports whether an index definition is durable (m.mu must be
  1020. // held).
  1021. func (m *SchemaManager) indexExistsUnsafe(name string) bool {
  1022. if _, ok := m.indexCache[strings.ToLower(name)]; ok {
  1023. return true
  1024. }
  1025. key := m.indexKey(name)
  1026. err := m.pool.WithClient(func(c *KVClient) error {
  1027. _, err := c.Read(key)
  1028. return err
  1029. })
  1030. return err == nil
  1031. }
  1032. // GetIndex retrieves an index by name.
  1033. func (m *SchemaManager) GetIndex(name string) (*Index, error) {
  1034. m.mu.Lock()
  1035. defer m.mu.Unlock()
  1036. cacheKey := strings.ToLower(name)
  1037. if index, ok := m.indexCache[cacheKey]; ok {
  1038. return cloneIndex(index), nil
  1039. }
  1040. key := m.indexKey(name)
  1041. var data string
  1042. err := m.pool.WithClient(func(c *KVClient) error {
  1043. var err error
  1044. data, err = c.Read(key)
  1045. return err
  1046. })
  1047. if err != nil {
  1048. if err == ErrKeyNotFound {
  1049. return nil, fmt.Errorf("%w: %s", ErrIndexNotFound, name)
  1050. }
  1051. return nil, err
  1052. }
  1053. var index Index
  1054. if err := json.Unmarshal([]byte(data), &index); err != nil {
  1055. return nil, fmt.Errorf("failed to parse index: %w", err)
  1056. }
  1057. m.indexCache[cacheKey] = &index
  1058. return cloneIndex(&index), nil
  1059. }
  1060. // ListIndexes returns all index names.
  1061. func (m *SchemaManager) ListIndexes() ([]string, error) {
  1062. m.mu.Lock()
  1063. defer m.mu.Unlock()
  1064. return m.indexListUnsafe()
  1065. }
  1066. // indexListUnsafe returns all index names, loading them from storage on first
  1067. // use (m.mu must be held).
  1068. func (m *SchemaManager) indexListUnsafe() ([]string, error) {
  1069. if m.indexListCached {
  1070. return append([]string(nil), m.indexListCache...), nil
  1071. }
  1072. key := m.indexListKey()
  1073. var data string
  1074. err := m.pool.WithClient(func(c *KVClient) error {
  1075. var err error
  1076. data, err = c.Read(key)
  1077. return err
  1078. })
  1079. if err == ErrKeyNotFound {
  1080. m.indexListCache = nil
  1081. m.indexListCached = true
  1082. return []string{}, nil
  1083. }
  1084. if err != nil {
  1085. return nil, err
  1086. }
  1087. var indexes []string
  1088. if err := json.Unmarshal([]byte(data), &indexes); err != nil {
  1089. return nil, fmt.Errorf("failed to parse index list: %w", err)
  1090. }
  1091. m.indexListCache = append([]string(nil), indexes...)
  1092. m.indexListCached = true
  1093. return indexes, nil
  1094. }
  1095. // ListTableIndexes returns all indexes for a table.
  1096. func (m *SchemaManager) ListTableIndexes(table string) ([]*Index, error) {
  1097. indexes, err := m.ListIndexes()
  1098. if err != nil {
  1099. return nil, err
  1100. }
  1101. var result []*Index
  1102. for _, name := range indexes {
  1103. idx, err := m.GetIndex(name)
  1104. if err != nil {
  1105. // An index dropped concurrently is simply absent; any other error
  1106. // (storage/IO or corrupt data) must not be silently swallowed.
  1107. if errors.Is(err, ErrIndexNotFound) {
  1108. continue
  1109. }
  1110. return nil, err
  1111. }
  1112. if strings.EqualFold(idx.Table, table) {
  1113. result = append(result, idx)
  1114. }
  1115. }
  1116. return result, nil
  1117. }
  1118. // addToIndexList adds an index name to the list.
  1119. func (m *SchemaManager) addToIndexList(name string) error {
  1120. key := m.indexListKey()
  1121. var indexes []string
  1122. var data string
  1123. err := m.pool.WithClient(func(c *KVClient) error {
  1124. var err error
  1125. data, err = c.Read(key)
  1126. return err
  1127. })
  1128. if err == nil {
  1129. json.Unmarshal([]byte(data), &indexes)
  1130. }
  1131. indexes = append(indexes, name)
  1132. newData, _ := json.Marshal(indexes)
  1133. err = m.pool.WithClient(func(c *KVClient) error {
  1134. return c.Write(key, string(newData))
  1135. })
  1136. if err == nil {
  1137. m.indexListCache = append([]string(nil), indexes...)
  1138. m.indexListCached = true
  1139. }
  1140. return err
  1141. }
  1142. // removeFromIndexList removes an index name from the list.
  1143. func (m *SchemaManager) removeFromIndexList(name string) error {
  1144. key := m.indexListKey()
  1145. var indexes []string
  1146. var data string
  1147. err := m.pool.WithClient(func(c *KVClient) error {
  1148. var err error
  1149. data, err = c.Read(key)
  1150. return err
  1151. })
  1152. if err != nil {
  1153. return nil
  1154. }
  1155. json.Unmarshal([]byte(data), &indexes)
  1156. var newIndexes []string
  1157. for _, idx := range indexes {
  1158. if !strings.EqualFold(idx, name) {
  1159. newIndexes = append(newIndexes, idx)
  1160. }
  1161. }
  1162. newData, _ := json.Marshal(newIndexes)
  1163. err = m.pool.WithClient(func(c *KVClient) error {
  1164. return c.Write(key, string(newData))
  1165. })
  1166. if err == nil {
  1167. m.indexListCache = append([]string(nil), newIndexes...)
  1168. m.indexListCached = true
  1169. }
  1170. return err
  1171. }
  1172. // AddColumn adds a new column to a table. When unique is non-nil the column's
  1173. // UNIQUE index is registered as part of the same statement, and checks are
  1174. // persisted with the column in the same schema snapshot.
  1175. //
  1176. // A DEFAULT is materialized into every existing row before the schema is
  1177. // published. NOT NULL, UNIQUE, CHECK, and index validation all read persisted
  1178. // row values, so a default that only existed in the catalog would be invisible
  1179. // to them: a UNIQUE index over the new column could not see the duplicate
  1180. // values every existing row shares, a CHECK predicate could not see a violating
  1181. // default, and an UPDATE to NULL would look non-null. The rewrite is the same
  1182. // shape as DropColumn: the table's exclusive gate keeps point writes and CAS
  1183. // commits out while rows are scanned, validated, and rewritten, the transform
  1184. // is idempotent, and the schema is saved last so an interrupted operation
  1185. // resumes against the old schema.
  1186. //
  1187. // The gate also makes the validation authoritative: NOT NULL without a default,
  1188. // duplicate UNIQUE values, and rows a new CHECK predicate rejects are rejected
  1189. // before the column, its checks, and its index are published, and they are
  1190. // published together in one batch write so a crash cannot leave the column
  1191. // visible without the constraints that validate it. A constant default is
  1192. // deterministic, so its UNIQUE prediction can run as a cheap pre-scan. A
  1193. // clock-reading default is evaluated at one instant sampled for this ALTER
  1194. // statement, and that instant is passed to every validation scan and to the
  1195. // rewrite, so a clock crossing between them cannot publish a row that violates
  1196. // the constraint the statement adds; the UNIQUE duplicate set is still
  1197. // collected during the rewrite so it covers exactly the values the index will
  1198. // see. A nullable column without a default needs no rewrite because a missing
  1199. // row field already reads as NULL. Like DROP COLUMN, the statement holds the
  1200. // catalog lock for the whole scan, so the cost is one table scan per validating
  1201. // constraint plus a table-wide stall per ADD COLUMN that has a default, an
  1202. // index, or a check.
  1203. func (m *SchemaManager) AddColumn(table string, column Column, checks []CheckConstraint, unique *Index) error {
  1204. tableLock := m.tableLock(table)
  1205. tableLock.Lock()
  1206. defer tableLock.Unlock()
  1207. m.mu.Lock()
  1208. defer m.mu.Unlock()
  1209. // One instant for the whole ALTER statement: every validation scan and the
  1210. // row rewrite must observe the same value, or a clock crossing between them
  1211. // could publish rows that violate the CHECK or UNIQUE constraint this
  1212. // statement adds.
  1213. now := m.defaultNow()
  1214. schema, err := m.getSchemaUnsafe(table)
  1215. if err != nil {
  1216. return err
  1217. }
  1218. if err := checkColumnAbsent(schema, column.Name); err != nil {
  1219. return err
  1220. }
  1221. if unique != nil {
  1222. if !strings.EqualFold(unique.Table, schema.Name) {
  1223. return fmt.Errorf("index %s belongs to table %s, not %s", unique.Name, unique.Table, schema.Name)
  1224. }
  1225. if m.indexExistsUnsafe(unique.Name) {
  1226. return fmt.Errorf("index already exists: %s", unique.Name)
  1227. }
  1228. // A clock-reading default is validated during the rewrite below so the
  1229. // duplicate set covers exactly the values this statement writes. The
  1230. // pre-scan is kept for constant and absent defaults, which are
  1231. // deterministic.
  1232. if column.DefaultExpr == "" {
  1233. if err := m.validateAddColumnUnique(table, column, unique, now); err != nil {
  1234. return err
  1235. }
  1236. }
  1237. }
  1238. if err := m.validateAddColumnChecks(table, column, checks, now); err != nil {
  1239. return err
  1240. }
  1241. // A required column with nothing to write into rows that already exist
  1242. // cannot be declared on a populated table.
  1243. if !column.Nullable && !columnHasDefault(column) {
  1244. hasRows, err := m.tableHasRows(table)
  1245. if err != nil {
  1246. return err
  1247. }
  1248. if hasRows {
  1249. return &NotNullViolationError{Table: schema.Name, Column: column.Name}
  1250. }
  1251. }
  1252. // An expression default is evaluated at the ALTER statement's instant. When
  1253. // the column is also UNIQUE, collect the values this rewrite writes and
  1254. // abort on a duplicate, so the index is validated against exactly the values
  1255. // it will see.
  1256. var seen map[string]struct{}
  1257. if unique != nil && column.DefaultExpr != "" {
  1258. seen = make(map[string]struct{})
  1259. }
  1260. if columnHasDefault(column) {
  1261. if err := m.applyRows(table, func(row Row) (bool, error) {
  1262. value, present := rowColumnValue(row, column.Name)
  1263. if !present {
  1264. var err error
  1265. value, _, err = m.columnDefaultValue(column, now)
  1266. if err != nil {
  1267. return false, err
  1268. }
  1269. row[column.Name] = value
  1270. }
  1271. if seen != nil {
  1272. if value == nil {
  1273. return !present, nil
  1274. }
  1275. encoded := encodeUniqueScalar(value)
  1276. if _, duplicate := seen[encoded]; duplicate {
  1277. return false, &UniqueViolationError{Constraint: unique.Name}
  1278. }
  1279. seen[encoded] = struct{}{}
  1280. }
  1281. return !present, nil
  1282. }); err != nil {
  1283. return err
  1284. }
  1285. }
  1286. return m.publishAddedColumn(schema, column, checks, unique)
  1287. }
  1288. // publishAddedColumn publishes a column, its checks, and, when present, its
  1289. // unique index in one atomic batch write (m.mu must be held): the schema
  1290. // snapshot, the index definition, and the index list always become durable
  1291. // together or not at all.
  1292. func (m *SchemaManager) publishAddedColumn(schema *Schema, column Column, checks []CheckConstraint, unique *Index) error {
  1293. // Publish a fresh snapshot instead of mutating readers' shared pointer.
  1294. schema = cloneSchema(schema)
  1295. schema.Columns = append(schema.Columns, column)
  1296. schema.Checks = append(schema.Checks, checks...)
  1297. schemaData, err := json.Marshal(schema)
  1298. if err != nil {
  1299. return fmt.Errorf("failed to serialize schema: %w", err)
  1300. }
  1301. ops := []BatchOp{{Op: batchPut, Key: []byte(m.schemaKey(schema.Name)), Value: schemaData}}
  1302. var indexList []string
  1303. if unique != nil {
  1304. unique.CreatedAt = time.Now()
  1305. indexData, err := json.Marshal(unique)
  1306. if err != nil {
  1307. return fmt.Errorf("failed to serialize index: %w", err)
  1308. }
  1309. indexList, err = m.indexListUnsafe()
  1310. if err != nil {
  1311. return err
  1312. }
  1313. indexList = append(indexList, unique.Name)
  1314. listData, err := json.Marshal(indexList)
  1315. if err != nil {
  1316. return fmt.Errorf("failed to serialize index list: %w", err)
  1317. }
  1318. ops = append(ops,
  1319. BatchOp{Op: batchPut, Key: []byte(m.indexKey(unique.Name)), Value: indexData},
  1320. BatchOp{Op: batchPut, Key: []byte(m.indexListKey()), Value: listData},
  1321. )
  1322. }
  1323. if err := m.pool.WithClient(func(c *KVClient) error {
  1324. _, err := c.BatchWrite(ops, nil)
  1325. return err
  1326. }); err != nil {
  1327. return fmt.Errorf("failed to publish column %s: %w", column.Name, err)
  1328. }
  1329. // Publish in-memory state only after the durable write.
  1330. m.cache[strings.ToLower(schema.Name)] = schema
  1331. if unique != nil {
  1332. m.indexCache[strings.ToLower(unique.Name)] = cloneIndex(unique)
  1333. m.indexListCache = append([]string(nil), indexList...)
  1334. m.indexListCached = true
  1335. }
  1336. m.bumpVersionLocked()
  1337. return nil
  1338. }
  1339. func checkColumnAbsent(schema *Schema, name string) error {
  1340. for _, col := range schema.Columns {
  1341. if strings.EqualFold(col.Name, name) {
  1342. return fmt.Errorf("column already exists: %s", name)
  1343. }
  1344. }
  1345. return nil
  1346. }
  1347. // DropColumn removes a column from a table.
  1348. func (m *SchemaManager) DropColumn(table, columnName string) error {
  1349. tableLock := m.tableLock(table)
  1350. tableLock.Lock()
  1351. defer tableLock.Unlock()
  1352. m.mu.Lock()
  1353. defer m.mu.Unlock()
  1354. schema, err := m.getSchemaUnsafe(table)
  1355. if err != nil {
  1356. return err
  1357. }
  1358. // Cannot drop primary key column
  1359. if schema.IsPrimaryKeyColumn(columnName) {
  1360. return fmt.Errorf("cannot drop primary key column: %s", columnName)
  1361. }
  1362. // Find and remove column
  1363. newColumns := make([]Column, 0, len(schema.Columns)-1)
  1364. found := false
  1365. for _, col := range schema.Columns {
  1366. if strings.EqualFold(col.Name, columnName) {
  1367. found = true
  1368. continue
  1369. }
  1370. newColumns = append(newColumns, col)
  1371. }
  1372. if !found {
  1373. return fmt.Errorf("column not found: %s", columnName)
  1374. }
  1375. schema = cloneSchema(schema)
  1376. schema.Columns = newColumns
  1377. if err := m.rewriteRows(table, func(row Row) bool {
  1378. for key := range row {
  1379. if strings.EqualFold(key, columnName) {
  1380. delete(row, key)
  1381. return true
  1382. }
  1383. }
  1384. return false
  1385. }); err != nil {
  1386. return err
  1387. }
  1388. // Update schema
  1389. return m.updateSchemaUnsafe(schema)
  1390. }
  1391. // RenameTable renames a table.
  1392. func (m *SchemaManager) RenameTable(oldName, newName string) error {
  1393. m.mu.Lock()
  1394. defer m.mu.Unlock()
  1395. // Check if old table exists
  1396. schema, err := m.getSchemaUnsafe(oldName)
  1397. if err != nil {
  1398. return err
  1399. }
  1400. // Check if new table name already exists
  1401. _, err = m.getSchemaUnsafe(newName)
  1402. if err == nil {
  1403. return fmt.Errorf("table already exists: %s", newName)
  1404. }
  1405. schema = cloneSchema(schema)
  1406. // Update schema name
  1407. schema.Name = newName
  1408. // Move durable rows from the old table's data prefix to the new one. Without
  1409. // this, ALTER TABLE ... RENAME leaves every row under the old key and the
  1410. // renamed table appears empty.
  1411. if err := m.renameDataKeys(oldName, newName); err != nil {
  1412. return err
  1413. }
  1414. // Repoint indexes that belonged to the old table.
  1415. if err := m.repointIndexesLocked(oldName, newName); err != nil {
  1416. return err
  1417. }
  1418. // Build the replacement catalog before switching schema names. The schema,
  1419. // catalog, and stale ROWID state change in one batch, so a crash cannot
  1420. // leave neither table name addressable after all row chunks have moved.
  1421. tables, err := m.ListTables()
  1422. if err != nil {
  1423. return err
  1424. }
  1425. foundOld := false
  1426. for i, name := range tables {
  1427. if strings.EqualFold(name, oldName) {
  1428. tables[i] = newName
  1429. foundOld = true
  1430. break
  1431. }
  1432. }
  1433. if !foundOld {
  1434. return fmt.Errorf("table not found in catalog: %s", oldName)
  1435. }
  1436. catalogData, err := json.Marshal(tables)
  1437. if err != nil {
  1438. return err
  1439. }
  1440. schemaData, err := json.Marshal(schema)
  1441. if err != nil {
  1442. return err
  1443. }
  1444. oldKey := m.schemaKey(oldName)
  1445. newKey := m.schemaKey(newName)
  1446. err = m.pool.WithClient(func(c *KVClient) error {
  1447. _, err := c.BatchWrite([]BatchOp{
  1448. {Op: batchPut, Key: []byte(newKey), Value: schemaData},
  1449. {Op: batchDelete, Key: []byte(oldKey)},
  1450. {Op: batchDelete, Key: []byte(m.rowIDKey(oldName))},
  1451. {Op: batchPut, Key: []byte(m.catalogKey()), Value: catalogData},
  1452. }, nil)
  1453. return err
  1454. })
  1455. if err != nil {
  1456. return err
  1457. }
  1458. // Update cache
  1459. oldLower := strings.ToLower(oldName)
  1460. newLower := strings.ToLower(newName)
  1461. delete(m.cache, oldLower)
  1462. m.rowIDMu.Lock()
  1463. delete(m.rowIDAlloc, oldLower)
  1464. m.rowIDMu.Unlock()
  1465. // Update cache
  1466. m.cache[newLower] = schema
  1467. m.bumpVersionLocked()
  1468. return nil
  1469. }
  1470. // renameDataKeys moves every durable row of a table from the old name's data
  1471. // prefix to the new name's prefix in a single atomic batch per page.
  1472. func (m *SchemaManager) renameDataKeys(oldName, newName string) error {
  1473. oldPrefix := []byte(fmt.Sprintf("%s:_data:%s:", m.database, strings.ToLower(oldName)))
  1474. newPrefix := fmt.Sprintf("%s:_data:%s:", m.database, strings.ToLower(newName))
  1475. return m.pool.WithClient(func(client *KVClient) (retErr error) {
  1476. cursor, err := client.Scan(oldPrefix)
  1477. if err != nil {
  1478. return err
  1479. }
  1480. defer func() {
  1481. if cerr := cursor.Close(); retErr == nil {
  1482. retErr = cerr
  1483. }
  1484. }()
  1485. ops := make([]BatchOp, 0, scanPageSize*2)
  1486. batchBytes := 8
  1487. flush := func() error {
  1488. if len(ops) == 0 {
  1489. return nil
  1490. }
  1491. if _, err := client.BatchWrite(ops, nil); err != nil {
  1492. return err
  1493. }
  1494. ops = ops[:0]
  1495. batchBytes = 8
  1496. return nil
  1497. }
  1498. for {
  1499. entries, done, err := cursor.Next()
  1500. if err != nil {
  1501. return err
  1502. }
  1503. for _, e := range entries {
  1504. suffix := string(e.Key[len(oldPrefix):])
  1505. newKey := []byte(newPrefix + suffix)
  1506. opBytes := 24 + len(newKey) + len(e.Value) + len(e.Key)
  1507. if len(ops)+2 > maxOperations || batchBytes+opBytes > bulkBatchByteBudget {
  1508. if err := flush(); err != nil {
  1509. return err
  1510. }
  1511. }
  1512. ops = append(ops,
  1513. BatchOp{Op: batchPut, Key: newKey, Value: e.Value},
  1514. BatchOp{Op: batchDelete, Key: append([]byte(nil), e.Key...)},
  1515. )
  1516. batchBytes += opBytes
  1517. }
  1518. if done {
  1519. return flush()
  1520. }
  1521. }
  1522. })
  1523. }
  1524. // updateIndexesOfTableLocked applies mutate to the durable definition of every
  1525. // index on table and persists the definitions it changed. mutate reports
  1526. // whether it modified the definition; unmodified indexes are left untouched.
  1527. // The changed definitions are written in one batch, so a table's indexes never
  1528. // split between the old and new shape. The caller holds m.mu; it reads the
  1529. // durable index list directly rather than calling the self-locking ListIndexes
  1530. // helper.
  1531. func (m *SchemaManager) updateIndexesOfTableLocked(table string, mutate func(*Index) bool) error {
  1532. var names []string
  1533. if m.indexListCached {
  1534. names = append([]string(nil), m.indexListCache...)
  1535. } else {
  1536. var data string
  1537. err := m.pool.WithClient(func(c *KVClient) error {
  1538. var rerr error
  1539. data, rerr = c.Read(m.indexListKey())
  1540. return rerr
  1541. })
  1542. if err == ErrKeyNotFound {
  1543. return nil
  1544. }
  1545. if err != nil {
  1546. return err
  1547. }
  1548. if err := json.Unmarshal([]byte(data), &names); err != nil {
  1549. return err
  1550. }
  1551. }
  1552. type indexUpdate struct {
  1553. index Index
  1554. key string
  1555. value []byte
  1556. }
  1557. var updates []indexUpdate
  1558. for _, name := range names {
  1559. key := m.indexKey(name)
  1560. var data string
  1561. err := m.pool.WithClient(func(c *KVClient) error {
  1562. var rerr error
  1563. data, rerr = c.Read(key)
  1564. return rerr
  1565. })
  1566. if err != nil {
  1567. if err == ErrKeyNotFound {
  1568. continue
  1569. }
  1570. return err
  1571. }
  1572. var idx Index
  1573. if err := json.Unmarshal([]byte(data), &idx); err != nil {
  1574. return err
  1575. }
  1576. if !strings.EqualFold(idx.Table, table) {
  1577. continue
  1578. }
  1579. if !mutate(&idx) {
  1580. continue
  1581. }
  1582. updated, err := json.Marshal(&idx)
  1583. if err != nil {
  1584. return err
  1585. }
  1586. updates = append(updates, indexUpdate{index: idx, key: key, value: updated})
  1587. }
  1588. if len(updates) == 0 {
  1589. return nil
  1590. }
  1591. ops := make([]BatchOp, 0, len(updates))
  1592. for _, update := range updates {
  1593. ops = append(ops, BatchOp{Op: batchPut, Key: []byte(update.key), Value: update.value})
  1594. }
  1595. if err := m.pool.WithClient(func(c *KVClient) error {
  1596. _, err := c.BatchWrite(ops, nil)
  1597. return err
  1598. }); err != nil {
  1599. return fmt.Errorf("update index definitions for table %s: %w", table, err)
  1600. }
  1601. for _, update := range updates {
  1602. if cached, ok := m.indexCache[strings.ToLower(update.index.Name)]; ok {
  1603. *cached = update.index
  1604. }
  1605. }
  1606. return nil
  1607. }
  1608. // repointIndexesLocked updates indexes whose table was renamed.
  1609. func (m *SchemaManager) repointIndexesLocked(oldName, newName string) error {
  1610. return m.updateIndexesOfTableLocked(oldName, func(idx *Index) bool {
  1611. idx.Table = newName
  1612. return true
  1613. })
  1614. }
  1615. // renameIndexColumnsLocked rewrites the stored definition of every index on
  1616. // table so a reference to oldName becomes newName. Index names stay unchanged:
  1617. // they are independent identifiers that SQLite does not derive from column
  1618. // names, and callers may have chosen them explicitly. A rename to an existing
  1619. // column name is rejected before this runs. Expression columns keep their SQL
  1620. // text; callers must reject a rename that such an expression depends on,
  1621. // because the text is not rewritten.
  1622. func (m *SchemaManager) renameIndexColumnsLocked(table, oldName, newName string) error {
  1623. return m.updateIndexesOfTableLocked(table, func(idx *Index) bool {
  1624. changed := false
  1625. for i := range idx.Columns {
  1626. // Expression columns persist SQL text, not a column reference; their
  1627. // text is left for the caller to drop and recreate the index.
  1628. if idx.Columns[i].Expression == "" && strings.EqualFold(idx.Columns[i].Name, oldName) {
  1629. idx.Columns[i].Name = newName
  1630. changed = true
  1631. }
  1632. }
  1633. return changed
  1634. })
  1635. }
  1636. // RenameColumn renames a column in a table. Column references in index
  1637. // definitions are rewritten; expression-index text is not, so a SQL caller must
  1638. // reject a rename that an expression depends on.
  1639. func (m *SchemaManager) RenameColumn(table, oldName, newName string) error {
  1640. tableLock := m.tableLock(table)
  1641. tableLock.Lock()
  1642. defer tableLock.Unlock()
  1643. m.mu.Lock()
  1644. defer m.mu.Unlock()
  1645. schema, err := m.getSchemaUnsafe(table)
  1646. if err != nil {
  1647. return err
  1648. }
  1649. // Check if new column name already exists
  1650. for _, col := range schema.Columns {
  1651. if strings.EqualFold(col.Name, newName) {
  1652. return fmt.Errorf("column already exists: %s", newName)
  1653. }
  1654. }
  1655. schema = cloneSchema(schema)
  1656. // Find and rename column
  1657. found := false
  1658. for i, col := range schema.Columns {
  1659. if strings.EqualFold(col.Name, oldName) {
  1660. schema.Columns[i].Name = newName
  1661. found = true
  1662. // Update primary key references if needed. Renaming keeps the column
  1663. // order, so a composite key's encoding is unchanged.
  1664. for i, pkColumn := range schema.PrimaryKeyColumns {
  1665. if strings.EqualFold(pkColumn, oldName) {
  1666. schema.PrimaryKeyColumns[i] = newName
  1667. }
  1668. }
  1669. if strings.EqualFold(schema.PrimaryKey, oldName) {
  1670. schema.PrimaryKey = newName
  1671. }
  1672. break
  1673. }
  1674. }
  1675. if !found {
  1676. return fmt.Errorf("column not found: %s", oldName)
  1677. }
  1678. if err := m.rewriteRows(table, func(row Row) bool {
  1679. for key, value := range row {
  1680. if strings.EqualFold(key, oldName) {
  1681. delete(row, key)
  1682. row[newName] = value
  1683. return true
  1684. }
  1685. }
  1686. return false
  1687. }); err != nil {
  1688. return err
  1689. }
  1690. // Publish the renamed schema before the index definitions: reads of the new
  1691. // column name resolve against rewritten rows as soon as the schema lands.
  1692. // Autocommit index DDL is not covered by this write, so a failure here leaves
  1693. // stale index metadata for the caller to drop and recreate; inside a
  1694. // transaction the whole statement is staged and published atomically.
  1695. if err := m.updateSchemaUnsafe(schema); err != nil {
  1696. return err
  1697. }
  1698. // Index metadata drives secondary-index values, UNIQUE enforcement,
  1699. // ON CONFLICT target resolution, and catalog introspection, so it must name
  1700. // the renamed column before any later statement uses the table.
  1701. return m.renameIndexColumnsLocked(table, oldName, newName)
  1702. }
  1703. // rewriteRows applies an idempotent name-keyed row transformation in bounded
  1704. // batches. Column DDL updates the schema only after all rows are rewritten, so
  1705. // an interrupted operation can safely resume against the old schema.
  1706. func (m *SchemaManager) rewriteRows(table string, transform func(Row) bool) error {
  1707. return m.applyRows(table, func(row Row) (bool, error) {
  1708. return transform(row), nil
  1709. })
  1710. }
  1711. // applyRows scans a table once and applies transform to every row. Rows for
  1712. // which transform reports a change are re-encoded and written in bounded
  1713. // batches; an error from transform aborts the scan. Callers hold the table's
  1714. // exclusive gate, so no writer can interleave between the scan and the schema
  1715. // update that follows it. Aborting after a batch was flushed is safe only
  1716. // because the DDL transforms are idempotent.
  1717. func (m *SchemaManager) applyRows(table string, transform func(Row) (bool, error)) error {
  1718. prefix := []byte(fmt.Sprintf("%s:_data:%s:", m.database, strings.ToLower(table)))
  1719. return m.pool.WithClient(func(client *KVClient) (retErr error) {
  1720. cursor, err := client.Scan(prefix)
  1721. if err != nil {
  1722. return err
  1723. }
  1724. defer func() {
  1725. if cerr := cursor.Close(); retErr == nil {
  1726. retErr = cerr
  1727. }
  1728. }()
  1729. ops := make([]BatchOp, 0, scanPageSize)
  1730. batchBytes := 8
  1731. flush := func() error {
  1732. if len(ops) == 0 {
  1733. return nil
  1734. }
  1735. if _, err := client.BatchWrite(ops, nil); err != nil {
  1736. return err
  1737. }
  1738. ops = ops[:0]
  1739. batchBytes = 8
  1740. return nil
  1741. }
  1742. for {
  1743. entries, done, err := cursor.Next()
  1744. if err != nil {
  1745. return err
  1746. }
  1747. for _, entry := range entries {
  1748. row, err := decodeRow(entry.Value)
  1749. if err != nil {
  1750. return err
  1751. }
  1752. changed, err := transform(row)
  1753. if err != nil {
  1754. return err
  1755. }
  1756. if !changed {
  1757. continue
  1758. }
  1759. value, err := encodeRow(row)
  1760. if err != nil {
  1761. return err
  1762. }
  1763. opBytes := 12 + len(entry.Key) + len(value)
  1764. if len(ops) == maxOperations || batchBytes+opBytes > bulkBatchByteBudget {
  1765. if err := flush(); err != nil {
  1766. return err
  1767. }
  1768. }
  1769. ops = append(ops, BatchOp{Op: batchPut, Key: append([]byte(nil), entry.Key...), Value: value})
  1770. batchBytes += opBytes
  1771. }
  1772. if done {
  1773. return flush()
  1774. }
  1775. }
  1776. })
  1777. }
  1778. // validateAddColumnUnique rejects an ADD COLUMN ... UNIQUE whose backfilled
  1779. // values would duplicate across existing rows. It reads rows as they will look
  1780. // after the rewrite (a row that already carries the field from an interrupted
  1781. // earlier attempt keeps its value) and mirrors ValidateUniqueIndex for a single
  1782. // plain column: NULLs do not collide. It is used only for a constant or absent
  1783. // default; a clock-reading default is validated by the rewrite itself because
  1784. // its values cannot be predicted. The caller holds the table's exclusive gate,
  1785. // so no writer can insert a conflicting row between this check and the
  1786. // publication of the index.
  1787. func (m *SchemaManager) validateAddColumnUnique(table string, column Column, index *Index, now time.Time) error {
  1788. seen := make(map[string]struct{})
  1789. return m.applyRows(table, func(row Row) (bool, error) {
  1790. value, ok := rowColumnValue(row, column.Name)
  1791. if !ok {
  1792. var err error
  1793. value, _, err = m.columnDefaultValue(column, now)
  1794. if err != nil {
  1795. return false, err
  1796. }
  1797. }
  1798. if value == nil {
  1799. return false, nil
  1800. }
  1801. encoded := encodeUniqueScalar(value)
  1802. if _, duplicate := seen[encoded]; duplicate {
  1803. return false, &UniqueViolationError{Constraint: index.Name}
  1804. }
  1805. seen[encoded] = struct{}{}
  1806. return false, nil
  1807. })
  1808. }
  1809. // columnHasDefault reports whether the column contributes a value to rows that
  1810. // omit it, whether that default is a stored constant or an expression.
  1811. func columnHasDefault(column Column) bool {
  1812. return column.Default != nil || column.DefaultExpr != ""
  1813. }
  1814. // validateAddColumnChecks rejects an ADD COLUMN ... CHECK whose predicate is
  1815. // already false for an existing row. Like validateAddColumnUnique it reads rows
  1816. // as they will look after the default backfill, and it runs before that rewrite
  1817. // so a rejected DDL leaves no row carrying the new field. The default is
  1818. // resolved through columnDefaultValue at the instant sampled once for the
  1819. // ALTER statement, so a clock-reading default reaches the predicate as the value
  1820. // the backfilled row will receive instead of NULL. The caller holds the table's
  1821. // exclusive gate, so no writer can insert a violating row between this
  1822. // validation and the publication of the check.
  1823. func (m *SchemaManager) validateAddColumnChecks(table string, column Column, checks []CheckConstraint, now time.Time) error {
  1824. if len(checks) == 0 {
  1825. return nil
  1826. }
  1827. eval := m.checkEvaluator()
  1828. if eval == nil {
  1829. return fmt.Errorf("cannot validate CHECK constraints on %s: no CHECK evaluator installed", table)
  1830. }
  1831. return m.applyRows(table, func(row Row) (bool, error) {
  1832. if _, ok := rowColumnValue(row, column.Name); !ok {
  1833. value, hasDefault, err := m.columnDefaultValue(column, now)
  1834. if err != nil {
  1835. return false, err
  1836. }
  1837. if hasDefault {
  1838. row[column.Name] = value
  1839. }
  1840. }
  1841. for _, check := range checks {
  1842. holds, err := eval(check.Expression, row)
  1843. if err != nil {
  1844. return false, fmt.Errorf("evaluate CHECK constraint %s on %s: %w", check.Label(), table, err)
  1845. }
  1846. if !holds {
  1847. return false, &CheckViolationError{Table: table, Constraint: check.Label()}
  1848. }
  1849. }
  1850. return false, nil
  1851. })
  1852. }
  1853. // tableHasRows reports whether a table holds at least one durable row.
  1854. func (m *SchemaManager) tableHasRows(table string) (bool, error) {
  1855. prefix := []byte(fmt.Sprintf("%s:_data:%s:", m.database, strings.ToLower(table)))
  1856. found := false
  1857. err := m.pool.WithClient(func(client *KVClient) (retErr error) {
  1858. cursor, err := client.ScanWithLimit(prefix, 1)
  1859. if err != nil {
  1860. return err
  1861. }
  1862. defer func() {
  1863. if cerr := cursor.Close(); retErr == nil {
  1864. retErr = cerr
  1865. }
  1866. }()
  1867. entries, _, err := cursor.Next()
  1868. if err != nil {
  1869. return err
  1870. }
  1871. found = len(entries) > 0
  1872. return nil
  1873. })
  1874. return found, err
  1875. }
  1876. // getSchemaUnsafe gets a schema without locking (internal use).
  1877. func (m *SchemaManager) getSchemaUnsafe(table string) (*Schema, error) {
  1878. tableLower := strings.ToLower(table)
  1879. // Check cache
  1880. if schema, ok := m.cache[tableLower]; ok {
  1881. return schema, nil
  1882. }
  1883. // Read from storage
  1884. key := m.schemaKey(table)
  1885. var data string
  1886. err := m.pool.WithClient(func(c *KVClient) error {
  1887. var err error
  1888. data, err = c.Read(key)
  1889. return err
  1890. })
  1891. if err != nil {
  1892. return nil, fmt.Errorf("table not found: %s", table)
  1893. }
  1894. var schema Schema
  1895. if err := json.Unmarshal([]byte(data), &schema); err != nil {
  1896. return nil, err
  1897. }
  1898. schema.normalizePrimaryKey()
  1899. m.cache[tableLower] = &schema
  1900. return &schema, nil
  1901. }
  1902. // updateSchemaUnsafe updates a schema without locking (internal use).
  1903. func (m *SchemaManager) updateSchemaUnsafe(schema *Schema) error {
  1904. key := m.schemaKey(schema.Name)
  1905. data, _ := json.Marshal(schema)
  1906. err := m.pool.WithClient(func(c *KVClient) error {
  1907. return c.Write(key, string(data))
  1908. })
  1909. if err != nil {
  1910. return err
  1911. }
  1912. // Update cache
  1913. m.cache[strings.ToLower(schema.Name)] = schema
  1914. m.bumpVersionLocked()
  1915. return nil
  1916. }