package db import "context" const requestCols = `id, user_id, chat_id, chat_type, source_message_id, card_message_id, card_is_photo, url, status, info, lang, created_at, updated_at` func scanRequest(sc interface{ Scan(...any) error }) (*Request, error) { var r Request err := sc.Scan(&r.ID, &r.UserID, &r.ChatID, &r.ChatType, &r.SourceMessageID, &r.CardMessageID, &r.CardIsPhoto, &r.URL, &r.Status, &r.Info, &r.Lang, &r.CreatedAt, &r.UpdatedAt) if err != nil { return nil, notFound(err) } return &r, nil } // InsertRequest stores a new request. func (s *Store) InsertRequest(ctx context.Context, r *Request) error { if r.CreatedAt == 0 { r.CreatedAt = NowMilli() } r.UpdatedAt = r.CreatedAt _, err := s.exec(ctx, `INSERT INTO requests (`+requestCols+`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, r.ID, r.UserID, r.ChatID, r.ChatType, r.SourceMessageID, r.CardMessageID, r.CardIsPhoto, r.URL, r.Status, r.Info, r.Lang, r.CreatedAt, r.UpdatedAt) return err } // GetRequest loads a request. func (s *Store) GetRequest(ctx context.Context, id string) (*Request, error) { return scanRequest(s.row(ctx, `SELECT `+requestCols+` FROM requests WHERE id = ?`, id)) } // SetRequestCard records which message shows the card. func (s *Store) SetRequestCard(ctx context.Context, id string, messageID int64, isPhoto bool) error { _, err := s.exec(ctx, `UPDATE requests SET card_message_id = ?, card_is_photo = ?, updated_at = ? WHERE id = ?`, messageID, isPhoto, NowMilli(), id) return err } // TransitionRequest moves a request from one status to another and reports // whether the row was in the expected status. It is the guard against two // button presses racing each other. func (s *Store) TransitionRequest(ctx context.Context, id, from, to string) (bool, error) { n, err := s.exec(ctx, `UPDATE requests SET status = ?, updated_at = ? WHERE id = ? AND status = ?`, to, NowMilli(), id, from) return n == 1, err }