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.

99 lines
2.3 KiB

3 years ago
  1. package mysql
  2. import (
  3. "context"
  4. "git.aiterp.net/lucifer/new-server/models"
  5. "github.com/jmoiron/sqlx"
  6. )
  7. type presetRecord struct {
  8. ID int `db:"id"`
  9. Name string `db:"name"`
  10. Hue float64 `db:"hue"`
  11. Saturation float64 `db:"saturation"`
  12. Kelvin int `db:"kelvin"`
  13. }
  14. type ColorPresetRepo struct {
  15. DBX *sqlx.DB
  16. }
  17. func (c *ColorPresetRepo) Find(ctx context.Context, id int) (models.ColorPreset, error) {
  18. var record presetRecord
  19. err := c.DBX.GetContext(ctx, &record, "SELECT * FROM color_preset WHERE id = ?", id)
  20. if err != nil {
  21. return models.ColorPreset{}, dbErr(err)
  22. }
  23. return c.fromRecords(record)[0], nil
  24. }
  25. func (c *ColorPresetRepo) FetchAll(ctx context.Context) ([]models.ColorPreset, error) {
  26. records := make([]presetRecord, 0, 16)
  27. err := c.DBX.SelectContext(ctx, &records, "SELECT * FROM color_preset")
  28. if err != nil {
  29. return nil, dbErr(err)
  30. }
  31. return c.fromRecords(records...), nil
  32. }
  33. func (c *ColorPresetRepo) Save(ctx context.Context, preset *models.ColorPreset) error {
  34. if preset.ID > 0 {
  35. _, err := c.DBX.ExecContext(
  36. ctx,
  37. "UPDATE color_preset SET name = ?, hue = ?, saturation = ?, kelvin = ? WHERE id = ?",
  38. preset.Name, preset.Value.Hue, preset.Value.Saturation, preset.Value.Kelvin, preset.ID,
  39. )
  40. if err != nil {
  41. return dbErr(err)
  42. }
  43. } else {
  44. rs, err := c.DBX.ExecContext(
  45. ctx,
  46. "INSERT INTO color_preset (name, hue, saturation, kelvin) VALUES (?, ?, ?, ?)",
  47. preset.Name, preset.Value.Hue, preset.Value.Saturation, preset.Value.Kelvin,
  48. )
  49. if err != nil {
  50. return dbErr(err)
  51. }
  52. id, err := rs.LastInsertId()
  53. if err != nil {
  54. return dbErr(err)
  55. }
  56. preset.ID = int(id)
  57. }
  58. return nil
  59. }
  60. func (c *ColorPresetRepo) Delete(ctx context.Context, preset *models.ColorPreset) error {
  61. _, err := c.DBX.ExecContext(ctx, "DELETE FROM color_preset WHERE id = ?", preset.ID)
  62. if err != nil {
  63. return dbErr(err)
  64. }
  65. preset.ID = 0
  66. return nil
  67. }
  68. func (c *ColorPresetRepo) fromRecords(records ...presetRecord) []models.ColorPreset {
  69. newList := make([]models.ColorPreset, len(records), len(records))
  70. for i, record := range records {
  71. newList[i] = models.ColorPreset{
  72. ID: record.ID,
  73. Name: record.Name,
  74. Value: models.ColorValue{
  75. Hue: record.Hue,
  76. Saturation: record.Saturation,
  77. Kelvin: record.Kelvin,
  78. },
  79. }
  80. }
  81. return newList
  82. }