You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

118 lines
2.4 KiB

  1. package mysql
  2. import (
  3. "context"
  4. "encoding/json"
  5. "git.aiterp.net/lucifer/new-server/models"
  6. "github.com/jmoiron/sqlx"
  7. )
  8. type sceneRecord struct {
  9. ID int `db:"id"`
  10. Name string `db:"name"`
  11. IntervalMS int64 `db:"interval_ms"`
  12. RoleJSON json.RawMessage `db:"roles"`
  13. }
  14. type SceneRepo struct {
  15. DBX *sqlx.DB
  16. }
  17. func (r *SceneRepo) Find(ctx context.Context, id int) (*models.Scene, error) {
  18. var scene sceneRecord
  19. err := r.DBX.GetContext(ctx, &scene, "SELECT * FROM scene WHERE id = ?", id)
  20. if err != nil {
  21. return nil, dbErr(err)
  22. }
  23. return r.populateOne(&scene)
  24. }
  25. func (r *SceneRepo) FetchAll(ctx context.Context) ([]models.Scene, error) {
  26. scenes := make([]sceneRecord, 0, 8)
  27. err := r.DBX.SelectContext(ctx, &scenes, "SELECT * FROM scene")
  28. if err != nil {
  29. return nil, dbErr(err)
  30. }
  31. return r.populate(scenes)
  32. }
  33. func (r *SceneRepo) Save(ctx context.Context, scene *models.Scene) error {
  34. j, err := json.Marshal(scene.Roles)
  35. if err != nil {
  36. return err
  37. }
  38. if scene.ID > 0 {
  39. _, err := r.DBX.ExecContext(
  40. ctx,
  41. "UPDATE scene SET name = ?, interval_ms = ?, roles = ? WHERE id = ?",
  42. scene.Name, scene.IntervalMS, j, scene.ID,
  43. )
  44. if err != nil {
  45. return dbErr(err)
  46. }
  47. } else {
  48. rs, err := r.DBX.ExecContext(
  49. ctx,
  50. "INSERT INTO scene (name, interval_ms, roles) VALUES (?, ?, ?)",
  51. scene.Name, scene.IntervalMS, j,
  52. )
  53. if err != nil {
  54. return dbErr(err)
  55. }
  56. id, err := rs.LastInsertId()
  57. if err != nil {
  58. return dbErr(err)
  59. }
  60. scene.ID = int(id)
  61. }
  62. return nil
  63. }
  64. func (r *SceneRepo) Delete(ctx context.Context, scene *models.Scene) error {
  65. _, err := r.DBX.ExecContext(ctx, "DELETE FROM scene WHERE id = ?", scene.ID)
  66. if err != nil {
  67. return dbErr(err)
  68. }
  69. scene.ID = 0
  70. return nil
  71. }
  72. func (r *SceneRepo) populateOne(record *sceneRecord) (*models.Scene, error) {
  73. records, err := r.populate([]sceneRecord{*record})
  74. if err != nil {
  75. return nil, err
  76. }
  77. return &records[0], nil
  78. }
  79. func (r *SceneRepo) populate(records []sceneRecord) ([]models.Scene, error) {
  80. res := make([]models.Scene, 0, len(records))
  81. for _, record := range records {
  82. scene := models.Scene{
  83. ID: record.ID,
  84. Name: record.Name,
  85. IntervalMS: record.IntervalMS,
  86. Roles: make([]models.SceneRole, 0, 8),
  87. }
  88. err := json.Unmarshal(record.RoleJSON, &scene.Roles)
  89. if err != nil {
  90. return nil, dbErr(err)
  91. }
  92. res = append(res, scene)
  93. }
  94. return res, nil
  95. }