orm.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. package orm
  2. import (
  3. "fmt"
  4. "net/http"
  5. "github.com/jinzhu/gorm"
  6. _ "github.com/jinzhu/gorm/dialects/mysql"
  7. )
  8. type Timetable [][]Activity
  9. type Person interface {
  10. GetCredential() *Credential
  11. }
  12. type Address struct {
  13. City string
  14. Street string
  15. ZipCode string
  16. Country string
  17. }
  18. type Location struct {
  19. Id string
  20. Name string
  21. Address *Address
  22. }
  23. type Room struct {
  24. Id string
  25. Name string
  26. Capacity int
  27. Location *Location
  28. }
  29. type Desk struct {
  30. Id string
  31. Name string
  32. Students []*Student
  33. Teacher *Teacher
  34. }
  35. type Student struct {
  36. gorm.Model
  37. Credential
  38. Class *Class
  39. }
  40. type Department struct {
  41. gorm.Model
  42. Name string
  43. Subjects []Subject
  44. Teachers []Teacher
  45. }
  46. type GetFn func(map[string]string) (interface{}, error)
  47. type PostFn func(map[string]string, *http.Request) (IDer, error)
  48. var currDB *gorm.DB
  49. func New(connection string) (*gorm.DB, error) {
  50. db, err := gorm.Open("mysql", connection)
  51. if err != nil {
  52. return nil, err
  53. }
  54. return db, nil
  55. }
  56. func Use(db *gorm.DB) {
  57. currDB = db
  58. }
  59. func DB() *gorm.DB {
  60. return currDB
  61. }
  62. func AutoMigrate() {
  63. if err := currDB.AutoMigrate(
  64. &School{},
  65. &Subject{},
  66. &Teacher{},
  67. &Class{},
  68. &Activity{},
  69. &Department{},
  70. &Student{},
  71. ).Error; err != nil {
  72. panic(err)
  73. }
  74. }
  75. func GetFunc(path string) (GetFn, error) {
  76. fn, ok := Get[path]
  77. if !ok {
  78. return nil, fmt.Errorf("Can't map %s!", path)
  79. }
  80. return fn, nil
  81. }
  82. func PostFunc(path string) (PostFn, error) {
  83. fn, ok := Post[path]
  84. if !ok {
  85. return nil, fmt.Errorf("Can't map %s!", path)
  86. }
  87. return fn, nil
  88. }