schema.go 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052
  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. // CreateTable creates a new table.
  305. func (m *SchemaManager) CreateTable(schema *Schema) error {
  306. m.mu.Lock()
  307. defer m.mu.Unlock()
  308. // Check if table already exists
  309. key := m.schemaKey(schema.Name)
  310. err := m.pool.WithClient(func(c *KVClient) error {
  311. _, err := c.Read(key)
  312. return err
  313. })
  314. if err == nil {
  315. return fmt.Errorf("table already exists: %s", schema.Name)
  316. }
  317. // Keep the cached schema private so callers cannot mutate a published
  318. // catalog snapshot after this operation returns.
  319. schema = cloneSchema(schema)
  320. schema.CreatedAt = time.Now()
  321. // Determine the primary key if not set. A schema with no declared key uses
  322. // the synthetic _rowid_ so user columns remain unconstrained and can hold
  323. // duplicate or NULL values.
  324. schema.normalizePrimaryKey()
  325. // Serialize schema
  326. data, err := json.Marshal(schema)
  327. if err != nil {
  328. return fmt.Errorf("failed to serialize schema: %w", err)
  329. }
  330. // Write schema
  331. err = m.pool.WithClient(func(c *KVClient) error {
  332. return c.Write(key, string(data))
  333. })
  334. if err != nil {
  335. return fmt.Errorf("failed to write schema: %w", err)
  336. }
  337. // Update catalog
  338. if err := m.addToCatalog(schema.Name); err != nil {
  339. // Rollback schema write
  340. m.pool.WithClient(func(c *KVClient) error {
  341. return c.Delete(key)
  342. })
  343. return err
  344. }
  345. // Update cache
  346. m.cache[strings.ToLower(schema.Name)] = schema
  347. m.bumpVersionLocked()
  348. return nil
  349. }
  350. // DropTable drops a table.
  351. func (m *SchemaManager) DropTable(name string) error {
  352. tableLock := m.tableLock(name)
  353. tableLock.Lock()
  354. defer tableLock.Unlock()
  355. m.mu.Lock()
  356. defer m.mu.Unlock()
  357. key := m.schemaKey(name)
  358. // Check if table exists
  359. err := m.pool.WithClient(func(c *KVClient) error {
  360. _, err := c.Read(key)
  361. return err
  362. })
  363. if err != nil {
  364. return fmt.Errorf("table not found: %s", name)
  365. }
  366. // Delete all rows by scanning their actual keys and batch-deleting them, so
  367. // a table drop no longer leaks durable rows.
  368. if err := m.deleteKeysWithPrefix([]byte(fmt.Sprintf("%s:_data:%s:", m.database, strings.ToLower(name)))); err != nil {
  369. return err
  370. }
  371. // Delete schema
  372. err = m.pool.WithClient(func(c *KVClient) error {
  373. return c.Delete(key)
  374. })
  375. if err != nil {
  376. return fmt.Errorf("failed to delete schema: %w", err)
  377. }
  378. // Delete ROWID state.
  379. m.pool.WithClient(func(c *KVClient) error {
  380. return c.Delete(m.rowIDKey(name))
  381. })
  382. // Update catalog
  383. if err := m.removeFromCatalog(name); err != nil {
  384. return err
  385. }
  386. // Update cache
  387. tableLower := strings.ToLower(name)
  388. delete(m.cache, tableLower)
  389. m.rowIDMu.Lock()
  390. delete(m.rowIDAlloc, tableLower)
  391. m.rowIDMu.Unlock()
  392. m.bumpVersionLocked()
  393. return nil
  394. }
  395. // GetSchema retrieves a table schema.
  396. func (m *SchemaManager) GetSchema(name string) (*Schema, error) {
  397. m.mu.RLock()
  398. if schema, ok := m.cache[strings.ToLower(name)]; ok {
  399. // Clone while still holding the read lock: the cached schema's
  400. // NextRowID field is mutated under the write lock, so cloning outside
  401. // the lock races with that mutation.
  402. cloned := cloneSchema(schema)
  403. m.mu.RUnlock()
  404. return cloned, nil
  405. }
  406. m.mu.RUnlock()
  407. m.mu.Lock()
  408. defer m.mu.Unlock()
  409. // Double-check after acquiring write lock
  410. if schema, ok := m.cache[strings.ToLower(name)]; ok {
  411. return cloneSchema(schema), nil
  412. }
  413. key := m.schemaKey(name)
  414. var data string
  415. err := m.pool.WithClient(func(c *KVClient) error {
  416. var err error
  417. data, err = c.Read(key)
  418. return err
  419. })
  420. if err != nil {
  421. if err == ErrKeyNotFound {
  422. return nil, fmt.Errorf("table not found: %s", name)
  423. }
  424. return nil, err
  425. }
  426. var schema Schema
  427. if err := json.Unmarshal([]byte(data), &schema); err != nil {
  428. return nil, fmt.Errorf("failed to parse schema: %w", err)
  429. }
  430. schema.normalizePrimaryKey()
  431. m.cache[strings.ToLower(name)] = &schema
  432. return cloneSchema(&schema), nil
  433. }
  434. func cloneSchema(schema *Schema) *Schema {
  435. if schema == nil {
  436. return nil
  437. }
  438. cloned := *schema
  439. cloned.Columns = append([]Column(nil), schema.Columns...)
  440. cloned.Checks = append([]CheckConstraint(nil), schema.Checks...)
  441. cloned.PrimaryKeyColumns = append([]string(nil), schema.PrimaryKeyColumns...)
  442. if schema.ForeignKeys != nil {
  443. cloned.ForeignKeys = make([]ForeignKeyConstraint, len(schema.ForeignKeys))
  444. for i, fk := range schema.ForeignKeys {
  445. cloned.ForeignKeys[i] = ForeignKeyConstraint{
  446. Name: fk.Name,
  447. Columns: append([]string(nil), fk.Columns...),
  448. RefTable: fk.RefTable,
  449. RefColumns: append([]string(nil), fk.RefColumns...),
  450. OnDelete: fk.OnDelete,
  451. OnUpdate: fk.OnUpdate,
  452. }
  453. }
  454. }
  455. return &cloned
  456. }
  457. func cloneIndex(index *Index) *Index {
  458. if index == nil {
  459. return nil
  460. }
  461. cloned := *index
  462. cloned.Columns = append([]IndexColumn(nil), index.Columns...)
  463. return &cloned
  464. }
  465. // TableExists checks if a table exists.
  466. func (m *SchemaManager) TableExists(name string) bool {
  467. _, err := m.GetSchema(name)
  468. return err == nil
  469. }
  470. // ListTables returns all table names.
  471. func (m *SchemaManager) ListTables() ([]string, error) {
  472. var data string
  473. err := m.pool.WithClient(func(c *KVClient) error {
  474. var err error
  475. data, err = c.Read(m.catalogKey())
  476. return err
  477. })
  478. if err != nil {
  479. if err == ErrKeyNotFound {
  480. return nil, nil
  481. }
  482. return nil, err
  483. }
  484. var tables []string
  485. if err := json.Unmarshal([]byte(data), &tables); err != nil {
  486. return nil, fmt.Errorf("failed to parse catalog: %w", err)
  487. }
  488. return tables, nil
  489. }
  490. // addToCatalog adds a table to the catalog.
  491. func (m *SchemaManager) addToCatalog(name string) error {
  492. tables, err := m.ListTables()
  493. if err != nil && err != ErrKeyNotFound {
  494. return err
  495. }
  496. // Check if already exists
  497. lowerName := strings.ToLower(name)
  498. for _, t := range tables {
  499. if strings.ToLower(t) == lowerName {
  500. return nil
  501. }
  502. }
  503. tables = append(tables, name)
  504. data, err := json.Marshal(tables)
  505. if err != nil {
  506. return err
  507. }
  508. return m.pool.WithClient(func(c *KVClient) error {
  509. return c.Write(m.catalogKey(), string(data))
  510. })
  511. }
  512. // removeFromCatalog removes a table from the catalog.
  513. func (m *SchemaManager) removeFromCatalog(name string) error {
  514. tables, err := m.ListTables()
  515. if err != nil {
  516. return err
  517. }
  518. lowerName := strings.ToLower(name)
  519. newTables := make([]string, 0, len(tables))
  520. for _, t := range tables {
  521. if strings.ToLower(t) != lowerName {
  522. newTables = append(newTables, t)
  523. }
  524. }
  525. data, err := json.Marshal(newTables)
  526. if err != nil {
  527. return err
  528. }
  529. return m.pool.WithClient(func(c *KVClient) error {
  530. return c.Write(m.catalogKey(), string(data))
  531. })
  532. }
  533. // InvalidateCache clears the cache for a table.
  534. func (m *SchemaManager) InvalidateCache(name string) {
  535. m.mu.Lock()
  536. defer m.mu.Unlock()
  537. tableLower := strings.ToLower(name)
  538. delete(m.cache, tableLower)
  539. m.rowIDMu.Lock()
  540. delete(m.rowIDAlloc, tableLower)
  541. m.rowIDMu.Unlock()
  542. }
  543. // ToAnalyzerTableInfo converts a Schema to analyzer.TableInfo.
  544. func (s *Schema) ToAnalyzerTableInfo() *analyzer.TableInfo {
  545. info := &analyzer.TableInfo{
  546. Name: s.Name,
  547. }
  548. for _, col := range s.Columns {
  549. info.Columns = append(info.Columns, analyzer.ColumnInfo{
  550. Name: col.Name,
  551. Type: analyzer.TypeFromName(col.Type),
  552. Nullable: col.Nullable,
  553. PrimaryKey: col.PrimaryKey,
  554. TableName: s.Name,
  555. Generated: col.GeneratedExpr != "",
  556. })
  557. }
  558. return info
  559. }
  560. // normalizePrimaryKey derives the ordered primary-key column list from the
  561. // legacy single-column field or from the columns marked PRIMARY KEY, and keeps
  562. // both representations consistent. Primary-key columns are implicitly NOT NULL.
  563. func (s *Schema) normalizePrimaryKey() {
  564. if len(s.PrimaryKeyColumns) == 0 {
  565. if s.PrimaryKey != "" {
  566. s.PrimaryKeyColumns = []string{s.PrimaryKey}
  567. } else {
  568. for _, col := range s.Columns {
  569. if col.PrimaryKey {
  570. s.PrimaryKeyColumns = append(s.PrimaryKeyColumns, col.Name)
  571. }
  572. }
  573. if len(s.PrimaryKeyColumns) == 0 {
  574. s.PrimaryKeyColumns = []string{"_rowid_"}
  575. }
  576. }
  577. }
  578. if len(s.PrimaryKeyColumns) == 1 {
  579. // A single-column key keeps the historical catalog shape: only the
  580. // scalar field, so existing schema bytes stay unchanged.
  581. s.PrimaryKey = s.PrimaryKeyColumns[0]
  582. s.PrimaryKeyColumns = nil
  583. } else {
  584. s.PrimaryKey = ""
  585. }
  586. for i := range s.Columns {
  587. if s.IsPrimaryKeyColumn(s.Columns[i].Name) {
  588. s.Columns[i].PrimaryKey = true
  589. s.Columns[i].Nullable = false
  590. }
  591. }
  592. }
  593. // PrimaryKeyList returns the ordered primary-key columns. A schema always has
  594. // at least one: an explicit key, or the synthetic _rowid_.
  595. func (s *Schema) PrimaryKeyList() []string {
  596. if len(s.PrimaryKeyColumns) > 0 {
  597. return append([]string(nil), s.PrimaryKeyColumns...)
  598. }
  599. if s.PrimaryKey != "" {
  600. return []string{s.PrimaryKey}
  601. }
  602. return []string{"_rowid_"}
  603. }
  604. // UsesSyntheticRowID reports whether the table declares no primary key, so rows
  605. // are stored under the engine-assigned ROWID.
  606. func (s *Schema) UsesSyntheticRowID() bool {
  607. columns := s.PrimaryKeyList()
  608. return len(columns) == 1 && strings.EqualFold(columns[0], "_rowid_")
  609. }
  610. // IsCompositePrimaryKey reports whether the primary key spans more than one
  611. // column.
  612. func (s *Schema) IsCompositePrimaryKey() bool {
  613. return len(s.PrimaryKeyList()) > 1
  614. }
  615. // IsSingleColumnPrimaryKey reports whether the primary key is exactly one
  616. // column, which is the only shape a durable point lookup may address with one
  617. // value.
  618. func (s *Schema) IsSingleColumnPrimaryKey() bool {
  619. return len(s.PrimaryKeyList()) == 1
  620. }
  621. // IsPrimaryKeyColumn reports whether name is one of the primary-key columns.
  622. func (s *Schema) IsPrimaryKeyColumn(name string) bool {
  623. for _, column := range s.PrimaryKeyList() {
  624. if strings.EqualFold(column, name) {
  625. return true
  626. }
  627. }
  628. return false
  629. }
  630. // PrimaryKeyTargetMatches reports whether columns names the complete
  631. // primary-key column set. Order is not significant: ON CONFLICT (b, a) on a
  632. // PRIMARY KEY (a, b) addresses the same key, because the encoded key is built
  633. // in declaration order either way. SQLite instead requires the declaration
  634. // order of a constraint; this engine already accepts arbitrary conflict-target
  635. // lists, so it matches the set rather than raising.
  636. func (s *Schema) PrimaryKeyTargetMatches(columns []string) bool {
  637. primary := s.PrimaryKeyList()
  638. if len(primary) != len(columns) {
  639. return false
  640. }
  641. for _, column := range primary {
  642. found := false
  643. for _, candidate := range columns {
  644. if strings.EqualFold(column, candidate) {
  645. found = true
  646. break
  647. }
  648. }
  649. if !found {
  650. return false
  651. }
  652. }
  653. return true
  654. }
  655. // PrimaryKeyForRow returns the row's primary key encoded the way the table's
  656. // durable row keys encode it. A single-column key keeps the historical
  657. // "<value>" form, so existing databases are read and written unchanged. A
  658. // composite key length-prefixes each component ("<len>:<value>" repeated), a
  659. // prefix-free encoding, so ("ab","c") and ("a","bc") cannot collide. A NULL or
  660. // missing component is a NOT NULL violation: no rowid is auto-assigned.
  661. func (s *Schema) PrimaryKeyForRow(row Row) (string, error) {
  662. columns := s.PrimaryKeyList()
  663. parts := make([]string, len(columns))
  664. for i, column := range columns {
  665. value, ok := rowColumnValue(row, column)
  666. if !ok || value == nil {
  667. return "", &NotNullViolationError{Table: s.Name, Column: column}
  668. }
  669. parts[i] = fmt.Sprintf("%v", value)
  670. }
  671. if len(parts) == 1 {
  672. return parts[0], nil
  673. }
  674. var b strings.Builder
  675. for _, part := range parts {
  676. b.WriteString(strconv.Itoa(len(part)))
  677. b.WriteByte(':')
  678. b.WriteString(part)
  679. }
  680. return b.String(), nil
  681. }
  682. // GetColumn returns a column by name.
  683. func (s *Schema) GetColumn(name string) (*Column, bool) {
  684. lowerName := strings.ToLower(name)
  685. for i := range s.Columns {
  686. if strings.ToLower(s.Columns[i].Name) == lowerName {
  687. return &s.Columns[i], true
  688. }
  689. }
  690. return nil, false
  691. }
  692. // GetNextRowID gets and increments the next ROWID for a table. Allocation is
  693. // serialized per table via the table's own allocator so inserts on different
  694. // tables never contend, and no global SchemaManager lock is held across the
  695. // durable derivation scan.
  696. func (m *SchemaManager) GetNextRowID(table string) (int64, error) {
  697. alloc := m.rowIDAllocatorFor(table)
  698. alloc.mu.Lock()
  699. defer alloc.mu.Unlock()
  700. next, err := m.nextRowIDLocked(alloc, table)
  701. if err != nil {
  702. return 0, err
  703. }
  704. alloc.next = next + 1
  705. return next, nil
  706. }
  707. // UpdateMaxRowID updates the next ROWID if the provided value is higher.
  708. func (m *SchemaManager) UpdateMaxRowID(table string, rowid int64) error {
  709. alloc := m.rowIDAllocatorFor(table)
  710. alloc.mu.Lock()
  711. defer alloc.mu.Unlock()
  712. next, err := m.nextRowIDLocked(alloc, table)
  713. if err != nil {
  714. return err
  715. }
  716. if rowid >= next {
  717. alloc.next = rowid + 1
  718. }
  719. return nil
  720. }
  721. // nextRowIDLocked returns the current next ROWID, deriving it from durable rows
  722. // on first use (must hold the per-table allocator lock).
  723. func (m *SchemaManager) nextRowIDLocked(alloc *rowIDAllocator, table string) (int64, error) {
  724. if alloc.init {
  725. return alloc.next, nil
  726. }
  727. next, err := m.deriveNextRowID(table)
  728. if err != nil {
  729. return 0, err
  730. }
  731. if next < 1 {
  732. next = 1
  733. }
  734. alloc.next = next
  735. alloc.init = true
  736. return alloc.next, nil
  737. }
  738. // deriveNextRowID scans durable row keys to recover max(rowid)+1, streaming
  739. // each page through decodeRow instead of materializing every value.
  740. func (m *SchemaManager) deriveNextRowID(table string) (int64, error) {
  741. prefix := []byte(fmt.Sprintf("%s:_data:%s:", m.database, strings.ToLower(table)))
  742. var maxRowID int64
  743. err := m.pool.WithClient(func(client *KVClient) (retErr error) {
  744. cursor, err := client.Scan(prefix)
  745. if err != nil {
  746. return err
  747. }
  748. defer func() {
  749. if err := cursor.Close(); retErr == nil {
  750. retErr = err
  751. }
  752. }()
  753. for {
  754. entries, done, err := cursor.Next()
  755. if err != nil {
  756. return err
  757. }
  758. for _, e := range entries {
  759. row, err := decodeRow(e.Value)
  760. if err != nil {
  761. return fmt.Errorf("failed to parse row while deriving ROWID: %w", err)
  762. }
  763. if rowid, ok := valueAsInt64(row["_rowid_"]); ok && rowid > maxRowID {
  764. maxRowID = rowid
  765. }
  766. }
  767. if done {
  768. return nil
  769. }
  770. }
  771. })
  772. if err != nil {
  773. return 0, err
  774. }
  775. return maxRowID + 1, nil
  776. }
  777. // deleteKeysWithPrefix streams the keys with the given prefix one page at a
  778. // time and atomically batch-deletes them, so a bulk operation never leaves
  779. // durable rows behind.
  780. func (m *SchemaManager) deleteKeysWithPrefix(prefix []byte) error {
  781. return m.pool.WithClient(func(client *KVClient) (retErr error) {
  782. cursor, err := client.ScanKeys(prefix)
  783. if err != nil {
  784. return err
  785. }
  786. defer func() {
  787. if err := cursor.Close(); retErr == nil {
  788. retErr = err
  789. }
  790. }()
  791. ops := make([]BatchOp, 0, scanPageSize)
  792. batchBytes := 8
  793. flush := func() error {
  794. if len(ops) == 0 {
  795. return nil
  796. }
  797. if _, err := client.BatchWrite(ops, nil); err != nil {
  798. return err
  799. }
  800. ops = ops[:0]
  801. batchBytes = 8
  802. return nil
  803. }
  804. for {
  805. entries, done, err := cursor.Next()
  806. if err != nil {
  807. return err
  808. }
  809. for _, e := range entries {
  810. opBytes := 12 + len(e.Key)
  811. if len(ops) == maxOperations || batchBytes+opBytes > bulkBatchByteBudget {
  812. if err := flush(); err != nil {
  813. return err
  814. }
  815. }
  816. ops = append(ops, BatchOp{Op: batchDelete, Key: append([]byte(nil), e.Key...)})
  817. batchBytes += opBytes
  818. }
  819. if done {
  820. return flush()
  821. }
  822. }
  823. })
  824. }
  825. func valueAsInt64(value interface{}) (int64, bool) {
  826. switch v := value.(type) {
  827. case int64:
  828. return v, true
  829. case int:
  830. return int64(v), true
  831. case float64:
  832. return int64(v), true
  833. default:
  834. return 0, false
  835. }
  836. }
  837. // getSchemaLocked retrieves schema (must hold lock).
  838. func (m *SchemaManager) getSchemaLocked(name string) (*Schema, error) {
  839. if schema, ok := m.cache[strings.ToLower(name)]; ok {
  840. return schema, nil
  841. }
  842. key := m.schemaKey(name)
  843. var data string
  844. err := m.pool.WithClient(func(c *KVClient) error {
  845. var err error
  846. data, err = c.Read(key)
  847. return err
  848. })
  849. if err != nil {
  850. if err == ErrKeyNotFound {
  851. return nil, fmt.Errorf("table not found: %s", name)
  852. }
  853. return nil, err
  854. }
  855. var schema Schema
  856. if err := json.Unmarshal([]byte(data), &schema); err != nil {
  857. return nil, fmt.Errorf("failed to parse schema: %w", err)
  858. }
  859. schema.normalizePrimaryKey()
  860. m.cache[strings.ToLower(name)] = &schema
  861. return &schema, nil
  862. }
  863. // saveSchemaLocked saves schema (must hold lock).
  864. func (m *SchemaManager) saveSchemaLocked(schema *Schema) error {
  865. data, err := json.Marshal(schema)
  866. if err != nil {
  867. return fmt.Errorf("failed to serialize schema: %w", err)
  868. }
  869. key := m.schemaKey(schema.Name)
  870. err = m.pool.WithClient(func(c *KVClient) error {
  871. return c.Write(key, string(data))
  872. })
  873. if err != nil {
  874. return fmt.Errorf("failed to write schema: %w", err)
  875. }
  876. m.cache[strings.ToLower(schema.Name)] = schema
  877. return nil
  878. }
  879. // Index management methods
  880. // indexKey returns the key for an index.
  881. func (m *SchemaManager) indexKey(name string) string {
  882. return fmt.Sprintf("%s:index:%s", m.database, strings.ToLower(name))
  883. }
  884. // indexListKey returns the key for the index list.
  885. func (m *SchemaManager) indexListKey() string {
  886. return fmt.Sprintf("%s:indexes", m.database)
  887. }
  888. // CreateIndex creates a new index.
  889. func (m *SchemaManager) CreateIndex(index *Index) error {
  890. m.mu.Lock()
  891. defer m.mu.Unlock()
  892. // Check if index already exists
  893. key := m.indexKey(index.Name)
  894. err := m.pool.WithClient(func(c *KVClient) error {
  895. _, err := c.Read(key)
  896. return err
  897. })
  898. if err == nil {
  899. return fmt.Errorf("index already exists: %s", index.Name)
  900. }
  901. // Verify table exists
  902. if _, err := m.getSchemaLocked(index.Table); err != nil {
  903. return fmt.Errorf("table not found: %s", index.Table)
  904. }
  905. // Save index
  906. index.CreatedAt = time.Now()
  907. data, err := json.Marshal(index)
  908. if err != nil {
  909. return fmt.Errorf("failed to serialize index: %w", err)
  910. }
  911. err = m.pool.WithClient(func(c *KVClient) error {
  912. return c.Write(key, string(data))
  913. })
  914. if err != nil {
  915. return fmt.Errorf("failed to write index: %w", err)
  916. }
  917. // Add to index list
  918. if err := m.addToIndexList(index.Name); err != nil {
  919. return err
  920. }
  921. m.indexCache[strings.ToLower(index.Name)] = cloneIndex(index)
  922. m.bumpVersionLocked()
  923. return nil
  924. }
  925. // DropIndex drops an index.
  926. func (m *SchemaManager) DropIndex(name string) error {
  927. m.mu.Lock()
  928. defer m.mu.Unlock()
  929. key := m.indexKey(name)
  930. err := m.pool.WithClient(func(c *KVClient) error {
  931. return c.Delete(key)
  932. })
  933. if err != nil {
  934. return fmt.Errorf("failed to delete index: %w", err)
  935. }
  936. if err := m.removeFromIndexList(name); err != nil {
  937. return err
  938. }
  939. delete(m.indexCache, strings.ToLower(name))
  940. m.bumpVersionLocked()
  941. return nil
  942. }
  943. // IndexExists checks if an index exists.
  944. func (m *SchemaManager) IndexExists(name string) bool {
  945. m.mu.RLock()
  946. defer m.mu.RUnlock()
  947. return m.indexExistsUnsafe(name)
  948. }
  949. // indexExistsUnsafe reports whether an index definition is durable (m.mu must be
  950. // held).
  951. func (m *SchemaManager) indexExistsUnsafe(name string) bool {
  952. if _, ok := m.indexCache[strings.ToLower(name)]; ok {
  953. return true
  954. }
  955. key := m.indexKey(name)
  956. err := m.pool.WithClient(func(c *KVClient) error {
  957. _, err := c.Read(key)
  958. return err
  959. })
  960. return err == nil
  961. }
  962. // GetIndex retrieves an index by name.
  963. func (m *SchemaManager) GetIndex(name string) (*Index, error) {
  964. m.mu.Lock()
  965. defer m.mu.Unlock()
  966. cacheKey := strings.ToLower(name)
  967. if index, ok := m.indexCache[cacheKey]; ok {
  968. return cloneIndex(index), nil
  969. }
  970. key := m.indexKey(name)
  971. var data string
  972. err := m.pool.WithClient(func(c *KVClient) error {
  973. var err error
  974. data, err = c.Read(key)
  975. return err
  976. })
  977. if err != nil {
  978. if err == ErrKeyNotFound {
  979. return nil, fmt.Errorf("%w: %s", ErrIndexNotFound, name)
  980. }
  981. return nil, err
  982. }
  983. var index Index
  984. if err := json.Unmarshal([]byte(data), &index); err != nil {
  985. return nil, fmt.Errorf("failed to parse index: %w", err)
  986. }
  987. m.indexCache[cacheKey] = &index
  988. return cloneIndex(&index), nil
  989. }
  990. // ListIndexes returns all index names.
  991. func (m *SchemaManager) ListIndexes() ([]string, error) {
  992. m.mu.Lock()
  993. defer m.mu.Unlock()
  994. return m.indexListUnsafe()
  995. }
  996. // indexListUnsafe returns all index names, loading them from storage on first
  997. // use (m.mu must be held).
  998. func (m *SchemaManager) indexListUnsafe() ([]string, error) {
  999. if m.indexListCached {
  1000. return append([]string(nil), m.indexListCache...), nil
  1001. }
  1002. key := m.indexListKey()
  1003. var data string
  1004. err := m.pool.WithClient(func(c *KVClient) error {
  1005. var err error
  1006. data, err = c.Read(key)
  1007. return err
  1008. })
  1009. if err == ErrKeyNotFound {
  1010. m.indexListCache = nil
  1011. m.indexListCached = true
  1012. return []string{}, nil
  1013. }
  1014. if err != nil {
  1015. return nil, err
  1016. }
  1017. var indexes []string
  1018. if err := json.Unmarshal([]byte(data), &indexes); err != nil {
  1019. return nil, fmt.Errorf("failed to parse index list: %w", err)
  1020. }
  1021. m.indexListCache = append([]string(nil), indexes...)
  1022. m.indexListCached = true
  1023. return indexes, nil
  1024. }
  1025. // ListTableIndexes returns all indexes for a table.
  1026. func (m *SchemaManager) ListTableIndexes(table string) ([]*Index, error) {
  1027. indexes, err := m.ListIndexes()
  1028. if err != nil {
  1029. return nil, err
  1030. }
  1031. var result []*Index
  1032. for _, name := range indexes {
  1033. idx, err := m.GetIndex(name)
  1034. if err != nil {
  1035. // An index dropped concurrently is simply absent; any other error
  1036. // (storage/IO or corrupt data) must not be silently swallowed.
  1037. if errors.Is(err, ErrIndexNotFound) {
  1038. continue
  1039. }
  1040. return nil, err
  1041. }
  1042. if strings.EqualFold(idx.Table, table) {
  1043. result = append(result, idx)
  1044. }
  1045. }
  1046. return result, nil
  1047. }
  1048. // addToIndexList adds an index name to the list.
  1049. func (m *SchemaManager) addToIndexList(name string) error {
  1050. key := m.indexListKey()
  1051. var indexes []string
  1052. var data string
  1053. err := m.pool.WithClient(func(c *KVClient) error {
  1054. var err error
  1055. data, err = c.Read(key)
  1056. return err
  1057. })
  1058. if err == nil {
  1059. json.Unmarshal([]byte(data), &indexes)
  1060. }
  1061. indexes = append(indexes, name)
  1062. newData, _ := json.Marshal(indexes)
  1063. err = m.pool.WithClient(func(c *KVClient) error {
  1064. return c.Write(key, string(newData))
  1065. })
  1066. if err == nil {
  1067. m.indexListCache = append([]string(nil), indexes...)
  1068. m.indexListCached = true
  1069. }
  1070. return err
  1071. }
  1072. // removeFromIndexList removes an index name from the list.
  1073. func (m *SchemaManager) removeFromIndexList(name string) error {
  1074. key := m.indexListKey()
  1075. var indexes []string
  1076. var data string
  1077. err := m.pool.WithClient(func(c *KVClient) error {
  1078. var err error
  1079. data, err = c.Read(key)
  1080. return err
  1081. })
  1082. if err != nil {
  1083. return nil
  1084. }
  1085. json.Unmarshal([]byte(data), &indexes)
  1086. var newIndexes []string
  1087. for _, idx := range indexes {
  1088. if !strings.EqualFold(idx, name) {
  1089. newIndexes = append(newIndexes, idx)
  1090. }
  1091. }
  1092. newData, _ := json.Marshal(newIndexes)
  1093. err = m.pool.WithClient(func(c *KVClient) error {
  1094. return c.Write(key, string(newData))
  1095. })
  1096. if err == nil {
  1097. m.indexListCache = append([]string(nil), newIndexes...)
  1098. m.indexListCached = true
  1099. }
  1100. return err
  1101. }
  1102. // AddColumn adds a new column to a table. When unique is non-nil the column's
  1103. // UNIQUE index is registered as part of the same statement, and checks are
  1104. // persisted with the column in the same schema snapshot.
  1105. //
  1106. // A DEFAULT is materialized into every existing row before the schema is
  1107. // published. NOT NULL, UNIQUE, CHECK, and index validation all read persisted
  1108. // row values, so a default that only existed in the catalog would be invisible
  1109. // to them: a UNIQUE index over the new column could not see the duplicate
  1110. // values every existing row shares, a CHECK predicate could not see a violating
  1111. // default, and an UPDATE to NULL would look non-null. The rewrite is the same
  1112. // shape as DropColumn: the table's exclusive gate keeps point writes and CAS
  1113. // commits out while rows are scanned, validated, and rewritten, the transform
  1114. // is idempotent, and the schema is saved last so an interrupted operation
  1115. // resumes against the old schema.
  1116. //
  1117. // The gate also makes the validation authoritative: NOT NULL without a default,
  1118. // duplicate UNIQUE values, and rows a new CHECK predicate rejects are rejected
  1119. // before the column, its checks, and its index are published, and they are
  1120. // published together in one batch write so a crash cannot leave the column
  1121. // visible without the constraints that validate it. A constant default is
  1122. // deterministic, so its UNIQUE prediction can run as a cheap pre-scan. A
  1123. // clock-reading default is evaluated at one instant sampled for this ALTER
  1124. // statement, and that instant is passed to every validation scan and to the
  1125. // rewrite, so a clock crossing between them cannot publish a row that violates
  1126. // the constraint the statement adds; the UNIQUE duplicate set is still
  1127. // collected during the rewrite so it covers exactly the values the index will
  1128. // see. A nullable column without a default needs no rewrite because a missing
  1129. // row field already reads as NULL. Like DROP COLUMN, the statement holds the
  1130. // catalog lock for the whole scan, so the cost is one table scan per validating
  1131. // constraint plus a table-wide stall per ADD COLUMN that has a default, an
  1132. // index, or a check.
  1133. func (m *SchemaManager) AddColumn(table string, column Column, checks []CheckConstraint, unique *Index) error {
  1134. tableLock := m.tableLock(table)
  1135. tableLock.Lock()
  1136. defer tableLock.Unlock()
  1137. m.mu.Lock()
  1138. defer m.mu.Unlock()
  1139. // One instant for the whole ALTER statement: every validation scan and the
  1140. // row rewrite must observe the same value, or a clock crossing between them
  1141. // could publish rows that violate the CHECK or UNIQUE constraint this
  1142. // statement adds.
  1143. now := m.defaultNow()
  1144. schema, err := m.getSchemaUnsafe(table)
  1145. if err != nil {
  1146. return err
  1147. }
  1148. if err := checkColumnAbsent(schema, column.Name); err != nil {
  1149. return err
  1150. }
  1151. if unique != nil {
  1152. if !strings.EqualFold(unique.Table, schema.Name) {
  1153. return fmt.Errorf("index %s belongs to table %s, not %s", unique.Name, unique.Table, schema.Name)
  1154. }
  1155. if m.indexExistsUnsafe(unique.Name) {
  1156. return fmt.Errorf("index already exists: %s", unique.Name)
  1157. }
  1158. // A clock-reading default is validated during the rewrite below so the
  1159. // duplicate set covers exactly the values this statement writes. The
  1160. // pre-scan is kept for constant and absent defaults, which are
  1161. // deterministic.
  1162. if column.DefaultExpr == "" {
  1163. if err := m.validateAddColumnUnique(table, column, unique, now); err != nil {
  1164. return err
  1165. }
  1166. }
  1167. }
  1168. if err := m.validateAddColumnChecks(table, column, checks, now); err != nil {
  1169. return err
  1170. }
  1171. // A required column with nothing to write into rows that already exist
  1172. // cannot be declared on a populated table.
  1173. if !column.Nullable && !columnHasDefault(column) {
  1174. hasRows, err := m.tableHasRows(table)
  1175. if err != nil {
  1176. return err
  1177. }
  1178. if hasRows {
  1179. return &NotNullViolationError{Table: schema.Name, Column: column.Name}
  1180. }
  1181. }
  1182. // An expression default is evaluated at the ALTER statement's instant. When
  1183. // the column is also UNIQUE, collect the values this rewrite writes and
  1184. // abort on a duplicate, so the index is validated against exactly the values
  1185. // it will see.
  1186. var seen map[string]struct{}
  1187. if unique != nil && column.DefaultExpr != "" {
  1188. seen = make(map[string]struct{})
  1189. }
  1190. if columnHasDefault(column) {
  1191. if err := m.applyRows(table, func(row Row) (bool, error) {
  1192. value, present := rowColumnValue(row, column.Name)
  1193. if !present {
  1194. var err error
  1195. value, _, err = m.columnDefaultValue(column, now)
  1196. if err != nil {
  1197. return false, err
  1198. }
  1199. row[column.Name] = value
  1200. }
  1201. if seen != nil {
  1202. if value == nil {
  1203. return !present, nil
  1204. }
  1205. encoded := encodeUniqueScalar(value)
  1206. if _, duplicate := seen[encoded]; duplicate {
  1207. return false, &UniqueViolationError{Constraint: unique.Name}
  1208. }
  1209. seen[encoded] = struct{}{}
  1210. }
  1211. return !present, nil
  1212. }); err != nil {
  1213. return err
  1214. }
  1215. }
  1216. return m.publishAddedColumn(schema, column, checks, unique)
  1217. }
  1218. // publishAddedColumn publishes a column, its checks, and, when present, its
  1219. // unique index in one atomic batch write (m.mu must be held): the schema
  1220. // snapshot, the index definition, and the index list always become durable
  1221. // together or not at all.
  1222. func (m *SchemaManager) publishAddedColumn(schema *Schema, column Column, checks []CheckConstraint, unique *Index) error {
  1223. // Publish a fresh snapshot instead of mutating readers' shared pointer.
  1224. schema = cloneSchema(schema)
  1225. schema.Columns = append(schema.Columns, column)
  1226. schema.Checks = append(schema.Checks, checks...)
  1227. schemaData, err := json.Marshal(schema)
  1228. if err != nil {
  1229. return fmt.Errorf("failed to serialize schema: %w", err)
  1230. }
  1231. ops := []BatchOp{{Op: batchPut, Key: []byte(m.schemaKey(schema.Name)), Value: schemaData}}
  1232. var indexList []string
  1233. if unique != nil {
  1234. unique.CreatedAt = time.Now()
  1235. indexData, err := json.Marshal(unique)
  1236. if err != nil {
  1237. return fmt.Errorf("failed to serialize index: %w", err)
  1238. }
  1239. indexList, err = m.indexListUnsafe()
  1240. if err != nil {
  1241. return err
  1242. }
  1243. indexList = append(indexList, unique.Name)
  1244. listData, err := json.Marshal(indexList)
  1245. if err != nil {
  1246. return fmt.Errorf("failed to serialize index list: %w", err)
  1247. }
  1248. ops = append(ops,
  1249. BatchOp{Op: batchPut, Key: []byte(m.indexKey(unique.Name)), Value: indexData},
  1250. BatchOp{Op: batchPut, Key: []byte(m.indexListKey()), Value: listData},
  1251. )
  1252. }
  1253. if err := m.pool.WithClient(func(c *KVClient) error {
  1254. _, err := c.BatchWrite(ops, nil)
  1255. return err
  1256. }); err != nil {
  1257. return fmt.Errorf("failed to publish column %s: %w", column.Name, err)
  1258. }
  1259. // Publish in-memory state only after the durable write.
  1260. m.cache[strings.ToLower(schema.Name)] = schema
  1261. if unique != nil {
  1262. m.indexCache[strings.ToLower(unique.Name)] = cloneIndex(unique)
  1263. m.indexListCache = append([]string(nil), indexList...)
  1264. m.indexListCached = true
  1265. }
  1266. m.bumpVersionLocked()
  1267. return nil
  1268. }
  1269. func checkColumnAbsent(schema *Schema, name string) error {
  1270. for _, col := range schema.Columns {
  1271. if strings.EqualFold(col.Name, name) {
  1272. return fmt.Errorf("column already exists: %s", name)
  1273. }
  1274. }
  1275. return nil
  1276. }
  1277. // DropColumn removes a column from a table.
  1278. func (m *SchemaManager) DropColumn(table, columnName string) error {
  1279. tableLock := m.tableLock(table)
  1280. tableLock.Lock()
  1281. defer tableLock.Unlock()
  1282. m.mu.Lock()
  1283. defer m.mu.Unlock()
  1284. schema, err := m.getSchemaUnsafe(table)
  1285. if err != nil {
  1286. return err
  1287. }
  1288. // Cannot drop primary key column
  1289. if schema.IsPrimaryKeyColumn(columnName) {
  1290. return fmt.Errorf("cannot drop primary key column: %s", columnName)
  1291. }
  1292. // Find and remove column
  1293. newColumns := make([]Column, 0, len(schema.Columns)-1)
  1294. found := false
  1295. for _, col := range schema.Columns {
  1296. if strings.EqualFold(col.Name, columnName) {
  1297. found = true
  1298. continue
  1299. }
  1300. newColumns = append(newColumns, col)
  1301. }
  1302. if !found {
  1303. return fmt.Errorf("column not found: %s", columnName)
  1304. }
  1305. schema = cloneSchema(schema)
  1306. schema.Columns = newColumns
  1307. if err := m.rewriteRows(table, func(row Row) bool {
  1308. for key := range row {
  1309. if strings.EqualFold(key, columnName) {
  1310. delete(row, key)
  1311. return true
  1312. }
  1313. }
  1314. return false
  1315. }); err != nil {
  1316. return err
  1317. }
  1318. // Update schema
  1319. return m.updateSchemaUnsafe(schema)
  1320. }
  1321. // RenameTable renames a table.
  1322. func (m *SchemaManager) RenameTable(oldName, newName string) error {
  1323. m.mu.Lock()
  1324. defer m.mu.Unlock()
  1325. // Check if old table exists
  1326. schema, err := m.getSchemaUnsafe(oldName)
  1327. if err != nil {
  1328. return err
  1329. }
  1330. // Check if new table name already exists
  1331. _, err = m.getSchemaUnsafe(newName)
  1332. if err == nil {
  1333. return fmt.Errorf("table already exists: %s", newName)
  1334. }
  1335. schema = cloneSchema(schema)
  1336. // Update schema name
  1337. schema.Name = newName
  1338. // Move durable rows from the old table's data prefix to the new one. Without
  1339. // this, ALTER TABLE ... RENAME leaves every row under the old key and the
  1340. // renamed table appears empty.
  1341. if err := m.renameDataKeys(oldName, newName); err != nil {
  1342. return err
  1343. }
  1344. // Repoint indexes that belonged to the old table.
  1345. if err := m.repointIndexesLocked(oldName, newName); err != nil {
  1346. return err
  1347. }
  1348. // Build the replacement catalog before switching schema names. The schema,
  1349. // catalog, and stale ROWID state change in one batch, so a crash cannot
  1350. // leave neither table name addressable after all row chunks have moved.
  1351. tables, err := m.ListTables()
  1352. if err != nil {
  1353. return err
  1354. }
  1355. foundOld := false
  1356. for i, name := range tables {
  1357. if strings.EqualFold(name, oldName) {
  1358. tables[i] = newName
  1359. foundOld = true
  1360. break
  1361. }
  1362. }
  1363. if !foundOld {
  1364. return fmt.Errorf("table not found in catalog: %s", oldName)
  1365. }
  1366. catalogData, err := json.Marshal(tables)
  1367. if err != nil {
  1368. return err
  1369. }
  1370. schemaData, err := json.Marshal(schema)
  1371. if err != nil {
  1372. return err
  1373. }
  1374. oldKey := m.schemaKey(oldName)
  1375. newKey := m.schemaKey(newName)
  1376. err = m.pool.WithClient(func(c *KVClient) error {
  1377. _, err := c.BatchWrite([]BatchOp{
  1378. {Op: batchPut, Key: []byte(newKey), Value: schemaData},
  1379. {Op: batchDelete, Key: []byte(oldKey)},
  1380. {Op: batchDelete, Key: []byte(m.rowIDKey(oldName))},
  1381. {Op: batchPut, Key: []byte(m.catalogKey()), Value: catalogData},
  1382. }, nil)
  1383. return err
  1384. })
  1385. if err != nil {
  1386. return err
  1387. }
  1388. // Update cache
  1389. oldLower := strings.ToLower(oldName)
  1390. newLower := strings.ToLower(newName)
  1391. delete(m.cache, oldLower)
  1392. m.rowIDMu.Lock()
  1393. delete(m.rowIDAlloc, oldLower)
  1394. m.rowIDMu.Unlock()
  1395. // Update cache
  1396. m.cache[newLower] = schema
  1397. m.bumpVersionLocked()
  1398. return nil
  1399. }
  1400. // renameDataKeys moves every durable row of a table from the old name's data
  1401. // prefix to the new name's prefix in a single atomic batch per page.
  1402. func (m *SchemaManager) renameDataKeys(oldName, newName string) error {
  1403. oldPrefix := []byte(fmt.Sprintf("%s:_data:%s:", m.database, strings.ToLower(oldName)))
  1404. newPrefix := fmt.Sprintf("%s:_data:%s:", m.database, strings.ToLower(newName))
  1405. return m.pool.WithClient(func(client *KVClient) (retErr error) {
  1406. cursor, err := client.Scan(oldPrefix)
  1407. if err != nil {
  1408. return err
  1409. }
  1410. defer func() {
  1411. if cerr := cursor.Close(); retErr == nil {
  1412. retErr = cerr
  1413. }
  1414. }()
  1415. ops := make([]BatchOp, 0, scanPageSize*2)
  1416. batchBytes := 8
  1417. flush := func() error {
  1418. if len(ops) == 0 {
  1419. return nil
  1420. }
  1421. if _, err := client.BatchWrite(ops, nil); err != nil {
  1422. return err
  1423. }
  1424. ops = ops[:0]
  1425. batchBytes = 8
  1426. return nil
  1427. }
  1428. for {
  1429. entries, done, err := cursor.Next()
  1430. if err != nil {
  1431. return err
  1432. }
  1433. for _, e := range entries {
  1434. suffix := string(e.Key[len(oldPrefix):])
  1435. newKey := []byte(newPrefix + suffix)
  1436. opBytes := 24 + len(newKey) + len(e.Value) + len(e.Key)
  1437. if len(ops)+2 > maxOperations || batchBytes+opBytes > bulkBatchByteBudget {
  1438. if err := flush(); err != nil {
  1439. return err
  1440. }
  1441. }
  1442. ops = append(ops,
  1443. BatchOp{Op: batchPut, Key: newKey, Value: e.Value},
  1444. BatchOp{Op: batchDelete, Key: append([]byte(nil), e.Key...)},
  1445. )
  1446. batchBytes += opBytes
  1447. }
  1448. if done {
  1449. return flush()
  1450. }
  1451. }
  1452. })
  1453. }
  1454. // updateIndexesOfTableLocked applies mutate to the durable definition of every
  1455. // index on table and persists the definitions it changed. mutate reports
  1456. // whether it modified the definition; unmodified indexes are left untouched.
  1457. // The changed definitions are written in one batch, so a table's indexes never
  1458. // split between the old and new shape. The caller holds m.mu; it reads the
  1459. // durable index list directly rather than calling the self-locking ListIndexes
  1460. // helper.
  1461. func (m *SchemaManager) updateIndexesOfTableLocked(table string, mutate func(*Index) bool) error {
  1462. var names []string
  1463. if m.indexListCached {
  1464. names = append([]string(nil), m.indexListCache...)
  1465. } else {
  1466. var data string
  1467. err := m.pool.WithClient(func(c *KVClient) error {
  1468. var rerr error
  1469. data, rerr = c.Read(m.indexListKey())
  1470. return rerr
  1471. })
  1472. if err == ErrKeyNotFound {
  1473. return nil
  1474. }
  1475. if err != nil {
  1476. return err
  1477. }
  1478. if err := json.Unmarshal([]byte(data), &names); err != nil {
  1479. return err
  1480. }
  1481. }
  1482. type indexUpdate struct {
  1483. index Index
  1484. key string
  1485. value []byte
  1486. }
  1487. var updates []indexUpdate
  1488. for _, name := range names {
  1489. key := m.indexKey(name)
  1490. var data string
  1491. err := m.pool.WithClient(func(c *KVClient) error {
  1492. var rerr error
  1493. data, rerr = c.Read(key)
  1494. return rerr
  1495. })
  1496. if err != nil {
  1497. if err == ErrKeyNotFound {
  1498. continue
  1499. }
  1500. return err
  1501. }
  1502. var idx Index
  1503. if err := json.Unmarshal([]byte(data), &idx); err != nil {
  1504. return err
  1505. }
  1506. if !strings.EqualFold(idx.Table, table) {
  1507. continue
  1508. }
  1509. if !mutate(&idx) {
  1510. continue
  1511. }
  1512. updated, err := json.Marshal(&idx)
  1513. if err != nil {
  1514. return err
  1515. }
  1516. updates = append(updates, indexUpdate{index: idx, key: key, value: updated})
  1517. }
  1518. if len(updates) == 0 {
  1519. return nil
  1520. }
  1521. ops := make([]BatchOp, 0, len(updates))
  1522. for _, update := range updates {
  1523. ops = append(ops, BatchOp{Op: batchPut, Key: []byte(update.key), Value: update.value})
  1524. }
  1525. if err := m.pool.WithClient(func(c *KVClient) error {
  1526. _, err := c.BatchWrite(ops, nil)
  1527. return err
  1528. }); err != nil {
  1529. return fmt.Errorf("update index definitions for table %s: %w", table, err)
  1530. }
  1531. for _, update := range updates {
  1532. if cached, ok := m.indexCache[strings.ToLower(update.index.Name)]; ok {
  1533. *cached = update.index
  1534. }
  1535. }
  1536. return nil
  1537. }
  1538. // repointIndexesLocked updates indexes whose table was renamed.
  1539. func (m *SchemaManager) repointIndexesLocked(oldName, newName string) error {
  1540. return m.updateIndexesOfTableLocked(oldName, func(idx *Index) bool {
  1541. idx.Table = newName
  1542. return true
  1543. })
  1544. }
  1545. // renameIndexColumnsLocked rewrites the stored definition of every index on
  1546. // table so a reference to oldName becomes newName. Index names stay unchanged:
  1547. // they are independent identifiers that SQLite does not derive from column
  1548. // names, and callers may have chosen them explicitly. A rename to an existing
  1549. // column name is rejected before this runs. Expression columns keep their SQL
  1550. // text; callers must reject a rename that such an expression depends on,
  1551. // because the text is not rewritten.
  1552. func (m *SchemaManager) renameIndexColumnsLocked(table, oldName, newName string) error {
  1553. return m.updateIndexesOfTableLocked(table, func(idx *Index) bool {
  1554. changed := false
  1555. for i := range idx.Columns {
  1556. // Expression columns persist SQL text, not a column reference; their
  1557. // text is left for the caller to drop and recreate the index.
  1558. if idx.Columns[i].Expression == "" && strings.EqualFold(idx.Columns[i].Name, oldName) {
  1559. idx.Columns[i].Name = newName
  1560. changed = true
  1561. }
  1562. }
  1563. return changed
  1564. })
  1565. }
  1566. // RenameColumn renames a column in a table. Column references in index
  1567. // definitions are rewritten; expression-index text is not, so a SQL caller must
  1568. // reject a rename that an expression depends on.
  1569. func (m *SchemaManager) RenameColumn(table, oldName, newName string) error {
  1570. tableLock := m.tableLock(table)
  1571. tableLock.Lock()
  1572. defer tableLock.Unlock()
  1573. m.mu.Lock()
  1574. defer m.mu.Unlock()
  1575. schema, err := m.getSchemaUnsafe(table)
  1576. if err != nil {
  1577. return err
  1578. }
  1579. // Check if new column name already exists
  1580. for _, col := range schema.Columns {
  1581. if strings.EqualFold(col.Name, newName) {
  1582. return fmt.Errorf("column already exists: %s", newName)
  1583. }
  1584. }
  1585. schema = cloneSchema(schema)
  1586. // Find and rename column
  1587. found := false
  1588. for i, col := range schema.Columns {
  1589. if strings.EqualFold(col.Name, oldName) {
  1590. schema.Columns[i].Name = newName
  1591. found = true
  1592. // Update primary key references if needed. Renaming keeps the column
  1593. // order, so a composite key's encoding is unchanged.
  1594. for i, pkColumn := range schema.PrimaryKeyColumns {
  1595. if strings.EqualFold(pkColumn, oldName) {
  1596. schema.PrimaryKeyColumns[i] = newName
  1597. }
  1598. }
  1599. if strings.EqualFold(schema.PrimaryKey, oldName) {
  1600. schema.PrimaryKey = newName
  1601. }
  1602. break
  1603. }
  1604. }
  1605. if !found {
  1606. return fmt.Errorf("column not found: %s", oldName)
  1607. }
  1608. if err := m.rewriteRows(table, func(row Row) bool {
  1609. for key, value := range row {
  1610. if strings.EqualFold(key, oldName) {
  1611. delete(row, key)
  1612. row[newName] = value
  1613. return true
  1614. }
  1615. }
  1616. return false
  1617. }); err != nil {
  1618. return err
  1619. }
  1620. // Publish the renamed schema before the index definitions: reads of the new
  1621. // column name resolve against rewritten rows as soon as the schema lands.
  1622. // Index DDL is not transactional (as elsewhere in this engine), so a failure
  1623. // here leaves stale index metadata for the caller to drop and recreate.
  1624. if err := m.updateSchemaUnsafe(schema); err != nil {
  1625. return err
  1626. }
  1627. // Index metadata drives secondary-index values, UNIQUE enforcement,
  1628. // ON CONFLICT target resolution, and catalog introspection, so it must name
  1629. // the renamed column before any later statement uses the table.
  1630. return m.renameIndexColumnsLocked(table, oldName, newName)
  1631. }
  1632. // rewriteRows applies an idempotent name-keyed row transformation in bounded
  1633. // batches. Column DDL updates the schema only after all rows are rewritten, so
  1634. // an interrupted operation can safely resume against the old schema.
  1635. func (m *SchemaManager) rewriteRows(table string, transform func(Row) bool) error {
  1636. return m.applyRows(table, func(row Row) (bool, error) {
  1637. return transform(row), nil
  1638. })
  1639. }
  1640. // applyRows scans a table once and applies transform to every row. Rows for
  1641. // which transform reports a change are re-encoded and written in bounded
  1642. // batches; an error from transform aborts the scan. Callers hold the table's
  1643. // exclusive gate, so no writer can interleave between the scan and the schema
  1644. // update that follows it. Aborting after a batch was flushed is safe only
  1645. // because the DDL transforms are idempotent.
  1646. func (m *SchemaManager) applyRows(table string, transform func(Row) (bool, error)) error {
  1647. prefix := []byte(fmt.Sprintf("%s:_data:%s:", m.database, strings.ToLower(table)))
  1648. return m.pool.WithClient(func(client *KVClient) (retErr error) {
  1649. cursor, err := client.Scan(prefix)
  1650. if err != nil {
  1651. return err
  1652. }
  1653. defer func() {
  1654. if cerr := cursor.Close(); retErr == nil {
  1655. retErr = cerr
  1656. }
  1657. }()
  1658. ops := make([]BatchOp, 0, scanPageSize)
  1659. batchBytes := 8
  1660. flush := func() error {
  1661. if len(ops) == 0 {
  1662. return nil
  1663. }
  1664. if _, err := client.BatchWrite(ops, nil); err != nil {
  1665. return err
  1666. }
  1667. ops = ops[:0]
  1668. batchBytes = 8
  1669. return nil
  1670. }
  1671. for {
  1672. entries, done, err := cursor.Next()
  1673. if err != nil {
  1674. return err
  1675. }
  1676. for _, entry := range entries {
  1677. row, err := decodeRow(entry.Value)
  1678. if err != nil {
  1679. return err
  1680. }
  1681. changed, err := transform(row)
  1682. if err != nil {
  1683. return err
  1684. }
  1685. if !changed {
  1686. continue
  1687. }
  1688. value, err := encodeRow(row)
  1689. if err != nil {
  1690. return err
  1691. }
  1692. opBytes := 12 + len(entry.Key) + len(value)
  1693. if len(ops) == maxOperations || batchBytes+opBytes > bulkBatchByteBudget {
  1694. if err := flush(); err != nil {
  1695. return err
  1696. }
  1697. }
  1698. ops = append(ops, BatchOp{Op: batchPut, Key: append([]byte(nil), entry.Key...), Value: value})
  1699. batchBytes += opBytes
  1700. }
  1701. if done {
  1702. return flush()
  1703. }
  1704. }
  1705. })
  1706. }
  1707. // validateAddColumnUnique rejects an ADD COLUMN ... UNIQUE whose backfilled
  1708. // values would duplicate across existing rows. It reads rows as they will look
  1709. // after the rewrite (a row that already carries the field from an interrupted
  1710. // earlier attempt keeps its value) and mirrors ValidateUniqueIndex for a single
  1711. // plain column: NULLs do not collide. It is used only for a constant or absent
  1712. // default; a clock-reading default is validated by the rewrite itself because
  1713. // its values cannot be predicted. The caller holds the table's exclusive gate,
  1714. // so no writer can insert a conflicting row between this check and the
  1715. // publication of the index.
  1716. func (m *SchemaManager) validateAddColumnUnique(table string, column Column, index *Index, now time.Time) error {
  1717. seen := make(map[string]struct{})
  1718. return m.applyRows(table, func(row Row) (bool, error) {
  1719. value, ok := rowColumnValue(row, column.Name)
  1720. if !ok {
  1721. var err error
  1722. value, _, err = m.columnDefaultValue(column, now)
  1723. if err != nil {
  1724. return false, err
  1725. }
  1726. }
  1727. if value == nil {
  1728. return false, nil
  1729. }
  1730. encoded := encodeUniqueScalar(value)
  1731. if _, duplicate := seen[encoded]; duplicate {
  1732. return false, &UniqueViolationError{Constraint: index.Name}
  1733. }
  1734. seen[encoded] = struct{}{}
  1735. return false, nil
  1736. })
  1737. }
  1738. // columnHasDefault reports whether the column contributes a value to rows that
  1739. // omit it, whether that default is a stored constant or an expression.
  1740. func columnHasDefault(column Column) bool {
  1741. return column.Default != nil || column.DefaultExpr != ""
  1742. }
  1743. // validateAddColumnChecks rejects an ADD COLUMN ... CHECK whose predicate is
  1744. // already false for an existing row. Like validateAddColumnUnique it reads rows
  1745. // as they will look after the default backfill, and it runs before that rewrite
  1746. // so a rejected DDL leaves no row carrying the new field. The default is
  1747. // resolved through columnDefaultValue at the instant sampled once for the
  1748. // ALTER statement, so a clock-reading default reaches the predicate as the value
  1749. // the backfilled row will receive instead of NULL. The caller holds the table's
  1750. // exclusive gate, so no writer can insert a violating row between this
  1751. // validation and the publication of the check.
  1752. func (m *SchemaManager) validateAddColumnChecks(table string, column Column, checks []CheckConstraint, now time.Time) error {
  1753. if len(checks) == 0 {
  1754. return nil
  1755. }
  1756. eval := m.checkEvaluator()
  1757. if eval == nil {
  1758. return fmt.Errorf("cannot validate CHECK constraints on %s: no CHECK evaluator installed", table)
  1759. }
  1760. return m.applyRows(table, func(row Row) (bool, error) {
  1761. if _, ok := rowColumnValue(row, column.Name); !ok {
  1762. value, hasDefault, err := m.columnDefaultValue(column, now)
  1763. if err != nil {
  1764. return false, err
  1765. }
  1766. if hasDefault {
  1767. row[column.Name] = value
  1768. }
  1769. }
  1770. for _, check := range checks {
  1771. holds, err := eval(check.Expression, row)
  1772. if err != nil {
  1773. return false, fmt.Errorf("evaluate CHECK constraint %s on %s: %w", check.Label(), table, err)
  1774. }
  1775. if !holds {
  1776. return false, &CheckViolationError{Table: table, Constraint: check.Label()}
  1777. }
  1778. }
  1779. return false, nil
  1780. })
  1781. }
  1782. // tableHasRows reports whether a table holds at least one durable row.
  1783. func (m *SchemaManager) tableHasRows(table string) (bool, error) {
  1784. prefix := []byte(fmt.Sprintf("%s:_data:%s:", m.database, strings.ToLower(table)))
  1785. found := false
  1786. err := m.pool.WithClient(func(client *KVClient) (retErr error) {
  1787. cursor, err := client.ScanWithLimit(prefix, 1)
  1788. if err != nil {
  1789. return err
  1790. }
  1791. defer func() {
  1792. if cerr := cursor.Close(); retErr == nil {
  1793. retErr = cerr
  1794. }
  1795. }()
  1796. entries, _, err := cursor.Next()
  1797. if err != nil {
  1798. return err
  1799. }
  1800. found = len(entries) > 0
  1801. return nil
  1802. })
  1803. return found, err
  1804. }
  1805. // getSchemaUnsafe gets a schema without locking (internal use).
  1806. func (m *SchemaManager) getSchemaUnsafe(table string) (*Schema, error) {
  1807. tableLower := strings.ToLower(table)
  1808. // Check cache
  1809. if schema, ok := m.cache[tableLower]; ok {
  1810. return schema, nil
  1811. }
  1812. // Read from storage
  1813. key := m.schemaKey(table)
  1814. var data string
  1815. err := m.pool.WithClient(func(c *KVClient) error {
  1816. var err error
  1817. data, err = c.Read(key)
  1818. return err
  1819. })
  1820. if err != nil {
  1821. return nil, fmt.Errorf("table not found: %s", table)
  1822. }
  1823. var schema Schema
  1824. if err := json.Unmarshal([]byte(data), &schema); err != nil {
  1825. return nil, err
  1826. }
  1827. schema.normalizePrimaryKey()
  1828. m.cache[tableLower] = &schema
  1829. return &schema, nil
  1830. }
  1831. // updateSchemaUnsafe updates a schema without locking (internal use).
  1832. func (m *SchemaManager) updateSchemaUnsafe(schema *Schema) error {
  1833. key := m.schemaKey(schema.Name)
  1834. data, _ := json.Marshal(schema)
  1835. err := m.pool.WithClient(func(c *KVClient) error {
  1836. return c.Write(key, string(data))
  1837. })
  1838. if err != nil {
  1839. return err
  1840. }
  1841. // Update cache
  1842. m.cache[strings.ToLower(schema.Name)] = schema
  1843. m.bumpVersionLocked()
  1844. return nil
  1845. }