orm.go 1.5 KB

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