orm.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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. &File{},
  68. &GeneratorType{},
  69. &Log{},
  70. ).Error; err != nil {
  71. panic(err)
  72. }
  73. }
  74. func GetFunc(path string) (GetFn, error) {
  75. fn, ok := Get[path]
  76. if !ok {
  77. return nil, fmt.Errorf("Can't map %s!", path)
  78. }
  79. return fn, nil
  80. }
  81. func PostFunc(path string) (PostFn, error) {
  82. fn, ok := Post[path]
  83. if !ok {
  84. return nil, fmt.Errorf("Can't map %s!", path)
  85. }
  86. return fn, nil
  87. }
  88. func GetNothing(args map[string]string) (interface{}, error) {
  89. return nil, nil
  90. }
  91. func PostNothing(args map[string]string, r *http.Request) (IDer, error) {
  92. return nil, nil
  93. }