2
0

constraints.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package storage
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. // PrimaryKeyViolationError preserves duplicate-key identity through wrapped
  7. // executor errors so wire adapters can report integrity SQLSTATE 23505.
  8. type PrimaryKeyViolationError struct {
  9. Table string
  10. Key string
  11. }
  12. func (e *PrimaryKeyViolationError) Error() string {
  13. return fmt.Sprintf("duplicate primary key: %s", e.Key)
  14. }
  15. // NotNullViolationError identifies the final row that violates a required column.
  16. type NotNullViolationError struct {
  17. Table string
  18. Column string
  19. }
  20. func (e *NotNullViolationError) Error() string {
  21. return fmt.Sprintf("NOT NULL constraint failed: %s.%s", e.Table, e.Column)
  22. }
  23. func validateNotNull(schema *Schema, row Row) error {
  24. for _, column := range schema.Columns {
  25. if !column.Nullable && row[column.Name] == nil {
  26. return &NotNullViolationError{Table: schema.Name, Column: column.Name}
  27. }
  28. }
  29. return nil
  30. }
  31. // applySchemaDefaults completes a row image that was built against an older
  32. // schema: columns the row predates receive their catalog default, and the row is
  33. // then validated against the required columns of the current schema.
  34. //
  35. // Write paths re-run it under the table gate because building a row image and
  36. // publishing it are separate steps. A transaction can normalize an INSERT before
  37. // a concurrent ADD COLUMN publishes a column and commit after it; the commit's
  38. // compare check cannot reject that row, because a new key is only checked for
  39. // absence. Re-applying the current schema keeps such a row from becoming a
  40. // durable NOT NULL violation, and gives it the default every other row received
  41. // from the backfill. An absent key is the only thing filled, so an explicit NULL
  42. // still does not select a default.
  43. func applySchemaDefaults(schema *Schema, row Row) error {
  44. for _, column := range schema.Columns {
  45. if _, ok := rowColumnValue(row, column.Name); ok {
  46. continue
  47. }
  48. if column.Default != nil {
  49. row[column.Name] = column.Default
  50. }
  51. }
  52. return validateNotNull(schema, row)
  53. }
  54. // rowColumnValue returns the value a row holds for a column, matching the column
  55. // name case-insensitively.
  56. func rowColumnValue(row Row, name string) (interface{}, bool) {
  57. if value, ok := row[name]; ok {
  58. return value, true
  59. }
  60. for key, value := range row {
  61. if strings.EqualFold(key, name) {
  62. return value, true
  63. }
  64. }
  65. return nil, false
  66. }