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.2 KiB

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