Files
Valve_research/builder/db/main.go
T
2026-11-19 14:06:28 +01:00

242 lines
6.3 KiB
Go

package db
import (
"context"
"database/sql"
"errors"
"time"
_ "modernc.org/sqlite" // pure-Go driver, no CGO needed
)
// Dates are ISO text "2006-01-02". Prices are int cents (EUR).
// Score is an int 0..10000 (10000 = 100.00%).
const schema = `
CREATE TABLE IF NOT EXISTS game (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
release TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS reviews (
game_id INTEGER NOT NULL REFERENCES game(id) ON DELETE CASCADE,
date TEXT NOT NULL,
positive INTEGER NOT NULL,
negative INTEGER NOT NULL,
positive_sum INTEGER NOT NULL,
negative_sum INTEGER NOT NULL,
score INTEGER NOT NULL,
label TEXT NOT NULL,
PRIMARY KEY (game_id, date)
);
CREATE TABLE IF NOT EXISTS prices (
game_id INTEGER NOT NULL REFERENCES game(id) ON DELETE CASCADE,
date TEXT NOT NULL,
price INTEGER NOT NULL,
discount INTEGER NOT NULL,
currency TEXT NOT NULL DEFAULT 'EUR',
PRIMARY KEY (game_id, date)
);
`
// ---------- enum ----------
type ScoreLabel string
const (
NoReviews ScoreLabel = "No user reviews"
OverwhelminglyNegative ScoreLabel = "Overwhelmingly Negative"
VeryNegative ScoreLabel = "Very Negative"
Negative ScoreLabel = "Negative"
MostlyNegative ScoreLabel = "Mostly Negative"
Mixed ScoreLabel = "Mixed"
MostlyPositive ScoreLabel = "Mostly Positive"
Positive ScoreLabel = "Positive"
VeryPositive ScoreLabel = "Very Positive"
OverwhelminglyPositive ScoreLabel = "Overwhelmingly Positive"
)
// ---------- types ----------
type Game struct {
ID int64
Name string
Release string
}
type ReviewDay struct {
GameID int64
Date string
Positive int64 // that day
Negative int64
// calculated
PositiveSum int64 // cumulative incl. this day
NegativeSum int64
Score int // 0..10000
Label ScoreLabel
}
type PriceDay struct {
GameID int64
Date string
Price int64 // cents
Discount int64 // percent
Currency string
}
func (r *ReviewDay) SolveScore() {
total := r.PositiveSum + r.NegativeSum
if total == 0 {
r.Score = 0
return
}
r.Score = int(r.PositiveSum * 10000 / total)
}
func (r *ReviewDay) ResolveLabel() {
total := r.PositiveSum + r.NegativeSum
pct := r.Score / 100
switch {
case total < 10:
r.Label = NoReviews
case pct >= 95 && total >= 500:
r.Label = OverwhelminglyPositive
case pct >= 80 && total >= 50:
r.Label = VeryPositive
case pct >= 80:
r.Label = Positive
case pct >= 70:
r.Label = MostlyPositive
case pct >= 40:
r.Label = Mixed
case pct >= 20:
r.Label = MostlyNegative
case total >= 500:
r.Label = OverwhelminglyNegative
case total >= 50:
r.Label = VeryNegative
default:
r.Label = Negative
}
}
// ---------- db ----------
type DB struct {
*sql.DB
}
// Open opens (or creates) the SQLite file and applies the schema.
func Open(path string) (*DB, error) {
sqlDB, err := sql.Open("sqlite", path+"?_pragma=foreign_keys(1)&_pragma=journal_mode(WAL)&_pragma=busy_timeout(5000)")
if err != nil {
return nil, err
}
sqlDB.SetMaxOpenConns(1)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := sqlDB.PingContext(ctx); err != nil {
return nil, err
}
if _, err := sqlDB.ExecContext(ctx, schema); err != nil {
return nil, err
}
return &DB{sqlDB}, nil
}
func (d *DB) CreateGame(ctx context.Context, g Game) error {
_, err := d.ExecContext(ctx,
`INSERT INTO game (id, name, release) VALUES (?, ?, ?)
ON CONFLICT(id) DO UPDATE SET name = excluded.name, release = excluded.release`,
g.ID, g.Name, g.Release)
return err
}
func (d *DB) ListGames(ctx context.Context) ([]Game, error) {
rows, err := d.QueryContext(ctx, `SELECT id, name, release FROM game ORDER BY id`)
if err != nil {
return nil, err
}
defer rows.Close()
var games []Game
for rows.Next() {
var g Game
if err := rows.Scan(&g.ID, &g.Name, &g.Release); err != nil {
return nil, err
}
games = append(games, g)
}
return games, rows.Err()
}
// SumsBefore returns the cumulative review sums of the last day before date.
// Returns zeros if there is none.
func (d *DB) SumsBefore(ctx context.Context, gameID int64, date string) (pos, neg int64, err error) {
err = d.QueryRowContext(ctx,
`SELECT positive_sum, negative_sum FROM reviews
WHERE game_id = ? AND date < ?
ORDER BY date DESC LIMIT 1`, gameID, date).Scan(&pos, &neg)
if errors.Is(err, sql.ErrNoRows) {
return 0, 0, nil
}
return pos, neg, err
}
// AddReviewDay adds the previous cumulative sums, computes score + label, upserts.
func (d *DB) AddReviewDay(ctx context.Context, r ReviewDay) (*ReviewDay, error) {
prevPos, prevNeg, err := d.SumsBefore(ctx, r.GameID, r.Date)
if err != nil {
return nil, err
}
r.PositiveSum = prevPos + r.Positive
r.NegativeSum = prevNeg + r.Negative
r.SolveScore()
r.ResolveLabel()
_, err = d.ExecContext(ctx,
`INSERT INTO reviews (game_id, date, positive, negative, positive_sum, negative_sum, score, label)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(game_id, date) DO UPDATE SET
positive = excluded.positive, negative = excluded.negative,
positive_sum = excluded.positive_sum, negative_sum = excluded.negative_sum,
score = excluded.score, label = excluded.label`,
r.GameID, r.Date, r.Positive, r.Negative, r.PositiveSum, r.NegativeSum, r.Score, string(r.Label))
if err != nil {
return nil, err
}
return &r, nil
}
func (d *DB) AddPriceDay(ctx context.Context, p PriceDay) error {
if p.Currency == "" {
p.Currency = "EUR"
}
_, err := d.ExecContext(ctx,
`INSERT INTO prices (game_id, date, price, discount, currency)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(game_id, date) DO UPDATE SET
price = excluded.price, discount = excluded.discount, currency = excluded.currency`,
p.GameID, p.Date, p.Price, p.Discount, p.Currency)
return err
}
func (d *DB) LatestReview(ctx context.Context, gameID int64) (*ReviewDay, error) {
var r ReviewDay
var label string
err := d.QueryRowContext(ctx,
`SELECT game_id, date, positive, negative, positive_sum, negative_sum, score, label
FROM reviews WHERE game_id = ? ORDER BY date DESC LIMIT 1`, gameID).
Scan(&r.GameID, &r.Date, &r.Positive, &r.Negative, &r.PositiveSum, &r.NegativeSum, &r.Score, &label)
if err != nil {
return nil, err
}
r.Label = ScoreLabel(label)
return &r, nil
}