schema.go 58 KB

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