schema.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package memdb
  2. import "fmt"
  3. // DBSchema contains the full database schema used for MemDB
  4. type DBSchema struct {
  5. Tables map[string]*TableSchema
  6. }
  7. // Validate is used to validate the database schema
  8. func (s *DBSchema) Validate() error {
  9. if s == nil {
  10. return fmt.Errorf("missing schema")
  11. }
  12. if len(s.Tables) == 0 {
  13. return fmt.Errorf("no tables defined")
  14. }
  15. for name, table := range s.Tables {
  16. if name != table.Name {
  17. return fmt.Errorf("table name mis-match for '%s'", name)
  18. }
  19. if err := table.Validate(); err != nil {
  20. return err
  21. }
  22. }
  23. return nil
  24. }
  25. // TableSchema contains the schema for a single table
  26. type TableSchema struct {
  27. Name string
  28. Indexes map[string]*IndexSchema
  29. }
  30. // Validate is used to validate the table schema
  31. func (s *TableSchema) Validate() error {
  32. if s.Name == "" {
  33. return fmt.Errorf("missing table name")
  34. }
  35. if len(s.Indexes) == 0 {
  36. return fmt.Errorf("missing table schemas for '%s'", s.Name)
  37. }
  38. if _, ok := s.Indexes["id"]; !ok {
  39. return fmt.Errorf("must have id index")
  40. }
  41. if !s.Indexes["id"].Unique {
  42. return fmt.Errorf("id index must be unique")
  43. }
  44. if _, ok := s.Indexes["id"].Indexer.(SingleIndexer); !ok {
  45. return fmt.Errorf("id index must be a SingleIndexer")
  46. }
  47. for name, index := range s.Indexes {
  48. if name != index.Name {
  49. return fmt.Errorf("index name mis-match for '%s'", name)
  50. }
  51. if err := index.Validate(); err != nil {
  52. return err
  53. }
  54. }
  55. return nil
  56. }
  57. // IndexSchema contains the schema for an index
  58. type IndexSchema struct {
  59. Name string
  60. AllowMissing bool
  61. Unique bool
  62. Indexer Indexer
  63. }
  64. func (s *IndexSchema) Validate() error {
  65. if s.Name == "" {
  66. return fmt.Errorf("missing index name")
  67. }
  68. if s.Indexer == nil {
  69. return fmt.Errorf("missing index function for '%s'", s.Name)
  70. }
  71. switch s.Indexer.(type) {
  72. case SingleIndexer:
  73. case MultiIndexer:
  74. default:
  75. return fmt.Errorf("indexer for '%s' must be a SingleIndexer or MultiIndexer", s.Name)
  76. }
  77. return nil
  78. }