constraints.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. package storage
  2. import (
  3. "fmt"
  4. "strings"
  5. "time"
  6. )
  7. // PrimaryKeyViolationError preserves duplicate-key identity through wrapped
  8. // executor errors so wire adapters can report integrity SQLSTATE 23505.
  9. type PrimaryKeyViolationError struct {
  10. Table string
  11. // Key is the primary key rendered for a reader, never the durable
  12. // length-prefixed encoding.
  13. Key string
  14. }
  15. func (e *PrimaryKeyViolationError) Error() string {
  16. return fmt.Sprintf("duplicate primary key: %s", e.Key)
  17. }
  18. // newPrimaryKeyViolation reports the duplicate key its write collided with. The
  19. // message renders the key from the row instead of the durable key: a composite
  20. // key is stored length-prefixed ("<len>:<value>" repeated), so splitting that
  21. // encoding to label the violation would corrupt any component that itself
  22. // contains the separator.
  23. func newPrimaryKeyViolation(table string, schema *Schema, row Row) *PrimaryKeyViolationError {
  24. return &PrimaryKeyViolationError{Table: table, Key: primaryKeyLabel(schema, row)}
  25. }
  26. // primaryKeyLabel renders a row's primary-key components for a reader: a
  27. // single-column key is that one component and a composite key is a parenthesized
  28. // tuple such as (1,11). A text component is rendered as a SQL literal with
  29. // embedded quotes doubled, so a value containing a comma or a quote stays
  30. // distinguishable from the tuple syntax.
  31. func primaryKeyLabel(schema *Schema, row Row) string {
  32. columns := schema.PrimaryKeyList()
  33. parts := make([]string, len(columns))
  34. for i, column := range columns {
  35. value, _ := rowColumnValue(row, column)
  36. parts[i] = primaryKeyComponent(value)
  37. }
  38. if len(parts) == 1 {
  39. return parts[0]
  40. }
  41. return "(" + strings.Join(parts, ",") + ")"
  42. }
  43. func primaryKeyComponent(value interface{}) string {
  44. switch v := value.(type) {
  45. case string:
  46. return "'" + strings.ReplaceAll(v, "'", "''") + "'"
  47. case []byte:
  48. return "'" + strings.ReplaceAll(string(v), "'", "''") + "'"
  49. default:
  50. return fmt.Sprintf("%v", v)
  51. }
  52. }
  53. // NotNullViolationError identifies the final row that violates a required column.
  54. type NotNullViolationError struct {
  55. Table string
  56. Column string
  57. }
  58. func (e *NotNullViolationError) Error() string {
  59. return fmt.Sprintf("NOT NULL constraint failed: %s.%s", e.Table, e.Column)
  60. }
  61. func validateNotNull(schema *Schema, row Row) error {
  62. for _, column := range schema.Columns {
  63. if !column.Nullable && row[column.Name] == nil {
  64. return &NotNullViolationError{Table: schema.Name, Column: column.Name}
  65. }
  66. }
  67. return nil
  68. }
  69. // CheckViolationError identifies the CHECK predicate a write violated. It is a
  70. // distinct type so the protocol layers can report SQLSTATE 23514.
  71. type CheckViolationError struct {
  72. Table string
  73. Constraint string
  74. }
  75. func (e *CheckViolationError) Error() string {
  76. return "CHECK constraint failed: " + e.Constraint
  77. }
  78. // validateChecks evaluates every persisted CHECK predicate against a complete
  79. // row image. The evaluator reports NULL and other unknown results as passing, so
  80. // SQL three-valued logic is preserved: a constraint only rejects a definite
  81. // false.
  82. func (m *SchemaManager) validateChecks(schema *Schema, row Row) error {
  83. if len(schema.Checks) == 0 {
  84. return nil
  85. }
  86. eval := m.checkEvaluator()
  87. if eval == nil {
  88. return fmt.Errorf("cannot validate CHECK constraints on %s: no CHECK evaluator installed", schema.Name)
  89. }
  90. for _, check := range schema.Checks {
  91. holds, err := eval(check.Expression, row)
  92. if err != nil {
  93. return fmt.Errorf("evaluate CHECK constraint %s on %s: %w", check.Label(), schema.Name, err)
  94. }
  95. if !holds {
  96. return &CheckViolationError{Table: schema.Name, Constraint: check.Label()}
  97. }
  98. }
  99. return nil
  100. }
  101. // validateRowConstraints enforces the NOT NULL and CHECK constraints a schema
  102. // declares against a complete row image. Every write path calls it after
  103. // defaults are applied and before the row becomes visible.
  104. func (m *SchemaManager) validateRowConstraints(schema *Schema, row Row) error {
  105. if err := validateNotNull(schema, row); err != nil {
  106. return err
  107. }
  108. return m.validateChecks(schema, row)
  109. }
  110. // applySchemaDefaults completes a row image that was built against an older
  111. // schema: columns the row predates receive their catalog default, and the row is
  112. // then validated against the required columns of the current schema.
  113. //
  114. // Write paths re-run it under the table gate because building a row image and
  115. // publishing it are separate steps. A transaction can normalize an INSERT before
  116. // a concurrent ADD COLUMN publishes a column and commit after it; the commit's
  117. // compare check cannot reject that row, because a new key is only checked for
  118. // absence. Re-applying the current schema keeps such a row from becoming a
  119. // durable NOT NULL violation, and gives it the default every other row received
  120. // from the backfill. An absent key is the only thing filled, so an explicit NULL
  121. // still does not select a default. Callers validate CHECK predicates separately
  122. // through validateRowConstraints/validateChecks so each write site can run them
  123. // against the final row image.
  124. //
  125. // A constant default is copied from the catalog. An expression default is
  126. // evaluated here instead, so a row that reaches storage without one (for
  127. // example a staged transaction row whose column was published later) receives a
  128. // value rather than freezing the DDL-time one. Ordinary INSERT/UPDATE resolve
  129. // expression defaults in the executor before the write; this is the fallback
  130. // for every other path.
  131. func (m *SchemaManager) applySchemaDefaults(schema *Schema, row Row) error {
  132. for _, column := range schema.Columns {
  133. if _, ok := rowColumnValue(row, column.Name); ok {
  134. continue
  135. }
  136. value, ok, err := m.columnDefaultValue(column, m.defaultNow())
  137. if err != nil {
  138. return err
  139. }
  140. if ok {
  141. row[column.Name] = value
  142. }
  143. }
  144. return validateNotNull(schema, row)
  145. }
  146. // columnDefaultValue returns the value a row receives for a column it omits.
  147. // A column with no default reports ok=false. DefaultExpr takes precedence over
  148. // Default; the two are never both set by DDL, which keeps constant defaults in
  149. // the catalog as values and clock-reading defaults as SQL text. now is the
  150. // instant the caller sampled for its statement; a constant default ignores it.
  151. func (m *SchemaManager) columnDefaultValue(column Column, now time.Time) (interface{}, bool, error) {
  152. if column.DefaultExpr != "" {
  153. eval := m.defaultEvaluator()
  154. if eval == nil {
  155. return nil, false, fmt.Errorf("column %q has a DEFAULT expression but no evaluator is installed", column.Name)
  156. }
  157. value, err := eval(column.DefaultExpr, now)
  158. if err != nil {
  159. return nil, false, fmt.Errorf("evaluate DEFAULT for column %q: %w", column.Name, err)
  160. }
  161. return value, true, nil
  162. }
  163. if column.Default != nil {
  164. return column.Default, true, nil
  165. }
  166. return nil, false, nil
  167. }
  168. // rowColumnValue returns the value a row holds for a column, matching the column
  169. // name case-insensitively.
  170. func rowColumnValue(row Row, name string) (interface{}, bool) {
  171. if value, ok := row[name]; ok {
  172. return value, true
  173. }
  174. for key, value := range row {
  175. if strings.EqualFold(key, name) {
  176. return value, true
  177. }
  178. }
  179. return nil, false
  180. }