Initial commit.

This commit is contained in:
Greyson Parrelli
2026-07-22 23:07:29 -04:00
commit 612a4e6227
38 changed files with 6106 additions and 0 deletions
+96
View File
@@ -0,0 +1,96 @@
// Package store persists game state as JSON blobs in SQLite.
package store
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"time"
_ "modernc.org/sqlite"
"github.com/greyson/super-auto-pets-board-game/internal/game"
)
// ErrNotFound is returned when a game doesn't exist.
var ErrNotFound = errors.New("game not found")
// Store wraps the SQLite database in the data directory.
type Store struct {
db *sql.DB
}
// Open creates the data directory if needed and opens (or initializes) the
// database inside it.
func Open(dataDir string) (*Store, error) {
if err := os.MkdirAll(dataDir, 0o755); err != nil {
return nil, fmt.Errorf("create data dir: %w", err)
}
dsn := fmt.Sprintf("file:%s?_pragma=journal_mode(WAL)&_pragma=busy_timeout(5000)",
filepath.Join(dataDir, "games.db"))
db, err := sql.Open("sqlite", dsn)
if err != nil {
return nil, err
}
// modernc.org/sqlite is happiest with a single writer connection.
db.SetMaxOpenConns(1)
if _, err := db.Exec(`
CREATE TABLE IF NOT EXISTS games (
id TEXT PRIMARY KEY,
code TEXT NOT NULL UNIQUE,
state TEXT NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
`); err != nil {
db.Close()
return nil, fmt.Errorf("init schema: %w", err)
}
return &Store{db: db}, nil
}
func (s *Store) Close() error { return s.db.Close() }
// Save upserts the full game state.
func (s *Store) Save(g *game.Game) error {
blob, err := json.Marshal(g)
if err != nil {
return err
}
now := time.Now().UnixMilli()
_, err = s.db.Exec(`
INSERT INTO games (id, code, state, created_at, updated_at)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET state = excluded.state, updated_at = excluded.updated_at
`, g.ID, g.Code, string(blob), now, now)
return err
}
// Load fetches a game by ID.
func (s *Store) Load(id string) (*game.Game, error) {
return s.loadWhere(`id = ?`, id)
}
// LoadByCode fetches a game by its join code.
func (s *Store) LoadByCode(code string) (*game.Game, error) {
return s.loadWhere(`code = ?`, code)
}
func (s *Store) loadWhere(cond string, arg any) (*game.Game, error) {
var blob string
err := s.db.QueryRow(`SELECT state FROM games WHERE `+cond, arg).Scan(&blob)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
if err != nil {
return nil, err
}
var g game.Game
if err := json.Unmarshal([]byte(blob), &g); err != nil {
return nil, fmt.Errorf("corrupt game state %v: %w", arg, err)
}
return &g, nil
}