schema.go 59 KB

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