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
99 lines
2.3 KiB
package mysql
|
|
|
|
import (
|
|
"context"
|
|
"git.aiterp.net/lucifer/new-server/models"
|
|
"github.com/jmoiron/sqlx"
|
|
)
|
|
|
|
type presetRecord struct {
|
|
ID int `db:"id"`
|
|
Name string `db:"name"`
|
|
Hue float64 `db:"hue"`
|
|
Saturation float64 `db:"saturation"`
|
|
Kelvin int `db:"kelvin"`
|
|
}
|
|
|
|
type ColorPresetRepo struct {
|
|
DBX *sqlx.DB
|
|
}
|
|
|
|
func (c *ColorPresetRepo) Find(ctx context.Context, id int) (models.ColorPreset, error) {
|
|
var record presetRecord
|
|
err := c.DBX.GetContext(ctx, &record, "SELECT * FROM color_preset WHERE id = ?", id)
|
|
if err != nil {
|
|
return models.ColorPreset{}, dbErr(err)
|
|
}
|
|
|
|
return c.fromRecords(record)[0], nil
|
|
}
|
|
|
|
func (c *ColorPresetRepo) FetchAll(ctx context.Context) ([]models.ColorPreset, error) {
|
|
records := make([]presetRecord, 0, 16)
|
|
err := c.DBX.SelectContext(ctx, &records, "SELECT * FROM color_preset")
|
|
if err != nil {
|
|
return nil, dbErr(err)
|
|
}
|
|
|
|
return c.fromRecords(records...), nil
|
|
}
|
|
|
|
func (c *ColorPresetRepo) Save(ctx context.Context, preset *models.ColorPreset) error {
|
|
if preset.ID > 0 {
|
|
_, err := c.DBX.ExecContext(
|
|
ctx,
|
|
"UPDATE color_preset SET name = ?, hue = ?, saturation = ?, kelvin = ? WHERE id = ?",
|
|
preset.Name, preset.Value.Hue, preset.Value.Saturation, preset.Value.Kelvin, preset.ID,
|
|
)
|
|
|
|
if err != nil {
|
|
return dbErr(err)
|
|
}
|
|
} else {
|
|
rs, err := c.DBX.ExecContext(
|
|
ctx,
|
|
"INSERT INTO color_preset (name, hue, saturation, kelvin) VALUES (?, ?, ?, ?)",
|
|
preset.Name, preset.Value.Hue, preset.Value.Saturation, preset.Value.Kelvin,
|
|
)
|
|
|
|
if err != nil {
|
|
return dbErr(err)
|
|
}
|
|
|
|
id, err := rs.LastInsertId()
|
|
if err != nil {
|
|
return dbErr(err)
|
|
}
|
|
|
|
preset.ID = int(id)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (c *ColorPresetRepo) Delete(ctx context.Context, preset *models.ColorPreset) error {
|
|
_, err := c.DBX.ExecContext(ctx, "DELETE FROM color_preset WHERE id = ?", preset.ID)
|
|
if err != nil {
|
|
return dbErr(err)
|
|
}
|
|
|
|
preset.ID = 0
|
|
return nil
|
|
}
|
|
|
|
func (c *ColorPresetRepo) fromRecords(records ...presetRecord) []models.ColorPreset {
|
|
newList := make([]models.ColorPreset, len(records), len(records))
|
|
for i, record := range records {
|
|
newList[i] = models.ColorPreset{
|
|
ID: record.ID,
|
|
Name: record.Name,
|
|
Value: models.ColorValue{
|
|
Hue: record.Hue,
|
|
Saturation: record.Saturation,
|
|
Kelvin: record.Kelvin,
|
|
},
|
|
}
|
|
}
|
|
|
|
return newList
|
|
}
|