60 lines
2.0 KiB
Go
60 lines
2.0 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"errors"
|
|
"math"
|
|
"time"
|
|
)
|
|
|
|
var ErrAppearanceInput = errors.New("invalid personal appearance settings")
|
|
|
|
func (s *Store) PersonalAppearance(ctx context.Context, domain, owner string) (version int64, data string, err error) {
|
|
defer func() { err = s.sqlError("personal appearance", err) }()
|
|
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
|
defer cancel()
|
|
err = s.DB.QueryRowContext(ctx, `SELECT version,data FROM personal_appearance WHERE domain_uuid=`+s.sqlParam(1)+` AND owner_uuid=`+s.sqlParam(2), domain, owner).Scan(&version, &data)
|
|
return
|
|
}
|
|
|
|
// The payload is presentation-owned JSON. This repository owns identity,
|
|
// current membership, and CAS; a stale version never overwrites another save.
|
|
func (s *Store) SavePersonalAppearance(ctx context.Context, domain, owner string, expected int64, data string) (err error) {
|
|
if expected < 0 || expected == math.MaxInt64 || len(data) > 16384 || !json.Valid([]byte(data)) {
|
|
return ErrAppearanceInput
|
|
}
|
|
defer func() { err = s.sqlError("personal appearance", err) }()
|
|
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
|
defer cancel()
|
|
tx, err := s.DB.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback()
|
|
if err = s.lockTaskWriter(ctx, tx); err != nil {
|
|
return err
|
|
}
|
|
if err = s.taskActor(ctx, tx, domain, owner, true); err != nil {
|
|
return err
|
|
}
|
|
var result sql.Result
|
|
if expected == 0 {
|
|
result, err = tx.ExecContext(ctx, `INSERT INTO personal_appearance(domain_uuid,owner_uuid,version,data) VALUES(`+s.sqlValues(4)+`) ON CONFLICT(domain_uuid,owner_uuid) DO NOTHING`, domain, owner, 1, data)
|
|
} else {
|
|
result, err = tx.ExecContext(ctx, `UPDATE personal_appearance SET version=`+s.sqlParam(1)+`,data=`+s.sqlParam(2)+` WHERE domain_uuid=`+s.sqlParam(3)+` AND owner_uuid=`+s.sqlParam(4)+` AND version=`+s.sqlParam(5), expected+1, data, domain, owner, expected)
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
n, err := result.RowsAffected()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if n != 1 {
|
|
return sql.ErrNoRows
|
|
}
|
|
return tx.Commit()
|
|
}
|