schema.go 57 KB

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