orm.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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 GetFn func(map[string]string) (interface{}, error)
  39. type PostFn func(map[string]string, *http.Request) (IDer, error)
  40. var currDB *gorm.DB
  41. func New(connection string) (*gorm.DB, error) {
  42. db, err := gorm.Open("mysql", connection)
  43. if err != nil {
  44. return nil, err
  45. }
  46. return db, nil
  47. }
  48. func Use(db *gorm.DB) {
  49. currDB = db
  50. }
  51. func DB() *gorm.DB {
  52. return currDB
  53. }
  54. func AutoMigrate() {
  55. if err := currDB.AutoMigrate(
  56. &School{},
  57. &Subject{},
  58. &Teacher{},
  59. &Class{},
  60. &Activity{},
  61. &Department{},
  62. &Student{},
  63. &Office{},
  64. &Administrative{},
  65. &Document{},
  66. &Job{},
  67. ).Error; err != nil {
  68. panic(err)
  69. }
  70. }
  71. func GetFunc(path string) (GetFn, error) {
  72. fn, ok := Get[path]
  73. if !ok {
  74. return nil, fmt.Errorf("Can't map %s!", path)
  75. }
  76. return fn, nil
  77. }
  78. func PostFunc(path string) (PostFn, error) {
  79. fn, ok := Post[path]
  80. if !ok {
  81. return nil, fmt.Errorf("Can't map %s!", path)
  82. }
  83. return fn, nil
  84. }
  85. func GetNothing(args map[string]string) (interface{}, error) {
  86. return nil, nil
  87. }
  88. func PostNothing(args map[string]string, r *http.Request) (IDer, error) {
  89. return nil, nil
  90. }