mercury/internal/database/sql/config.go
2023-09-04 03:33:13 +02:00

51 lines
1.4 KiB
Go

package sql
import (
"context"
"emperror.dev/errors"
"git.sleepycat.moe/sam/mercury/internal/database"
"github.com/keegancsmith/sqlf"
)
// ConfigStore is the interface to configs in the database.
type ConfigStore struct {
q Querier
}
// NewConfigStore creates a new ConfigStore instance.
func NewConfigStore(q Querier) *ConfigStore {
return &ConfigStore{q: q}
}
func (s *ConfigStore) initConfig(ctx context.Context) error {
q := sqlf.Sprintf(`INSERT INTO config
(id, name)
VALUES (1, %s)
ON CONFLICT (id) DO NOTHING`, database.DefaultConfig.Name)
err := Exec(ctx, s.q, q)
return errors.Wrap(err, "executing query")
}
func (s *ConfigStore) Get(ctx context.Context) (database.Config, error) {
q := sqlf.Sprintf("SELECT * FROM config WHERE id = 1")
return Get[database.Config](ctx, s.q, q)
}
func (s *ConfigStore) Set(ctx context.Context, cur, new database.Config) (database.Config, error) {
q := sqlf.Sprintf("UPDATE config SET")
if cur.Name != new.Name {
q = sqlf.Sprintf("%v name = %v,", q, new.Name)
}
if cur.AdminID != new.AdminID {
q = sqlf.Sprintf("%v admin_id = %v,", q, new.AdminID)
}
if cur.InternalApplication != new.InternalApplication {
q = sqlf.Sprintf("%v internal_application = %v,", q, new.InternalApplication)
}
q = sqlf.Sprintf("%v id = %v WHERE id = %v RETURNING *", q, cur.ID, cur.ID)
return Get[database.Config](ctx, s.q, q)
}