Documentation
¶
Overview ¶
Package sqlstore is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package sqlstore persists and ranks self-hosted leaderboard records in SQLite or Postgres.
Index ¶
- Constants
- Variables
- type Dialect
- type Store
- func (s *Store) AccountRecords(ctx context.Context, board, period, account string) ([]selfhost.Record, error)
- func (s *Store) Around(ctx context.Context, board selfhost.Board, period, account string, radius int, ...) ([]selfhost.Entry, int, error)
- func (s *Store) Close() error
- func (s *Store) Configure(boards []selfhost.Board)
- func (s *Store) DB() *sql.DB
- func (s *Store) DeleteAccount(ctx context.Context, board, period, account string) error
- func (s *Store) DeleteHidden(ctx context.Context, board, account string) error
- func (s *Store) Drop(ctx context.Context, board, period string) error
- func (s *Store) DropPeriod(ctx context.Context, board, period string) (int, error)
- func (s *Store) Friends(ctx context.Context, board selfhost.Board, period string, accounts []string, ...) ([]selfhost.Entry, int, error)
- func (s *Store) GetHidden(ctx context.Context, board, account string) (selfhost.Hidden, bool, error)
- func (s *Store) Hidden(ctx context.Context, board string, now time.Time) ([]selfhost.Hidden, error)
- func (s *Store) Load(ctx context.Context, fn func(selfhost.Record) error) error
- func (s *Store) LoadAdmin(ctx context.Context) (selfhost.AdminState, error)
- func (s *Store) Periods(ctx context.Context, board string) ([][2]string, error)
- func (s *Store) Rank(ctx context.Context, board selfhost.Board, period, account string, ...) (selfhost.Entry, error)
- func (s *Store) Records(ctx context.Context, board, period string) ([]selfhost.Record, error)
- func (s *Store) Resets(ctx context.Context, board string) ([]time.Time, error)
- func (s *Store) Save(ctx context.Context, rec selfhost.Record) error
- func (s *Store) SaveHidden(ctx context.Context, h selfhost.Hidden) error
- func (s *Store) SaveReset(ctx context.Context, r selfhost.BoardReset) error
- func (s *Store) Submit(ctx context.Context, sub selfhost.RankSubmission) (selfhost.RankResult, error)
- func (s *Store) Top(ctx context.Context, board selfhost.Board, period string, offset, limit int, ...) ([]selfhost.Entry, int, error)
- func (s *Store) Total(ctx context.Context, board selfhost.Board, period string, ...) (int, error)
Examples ¶
Constants ¶
const SchemaVersion = 4
SchemaVersion is the version of the leaderboard schema New migrates a database to. Version 2 adds each record's subscore and metadata; version 3 adds the tables of hidden accounts and manual resets; version 4 replaces the legacy leaderboard_order index with directional ranking indexes (leaderboard_rank_desc and leaderboard_rank_asc) matching the exact tie-break order.
Variables ¶
var Postgres = Dialect{Name: "postgres", Blob: "BIGINT", Numbered: true, MigrateLock: `SELECT pg_advisory_xact_lock(16801680)`, LockRecord: `SELECT pg_advisory_xact_lock(16801680, hashtext(?))`}
Postgres is the dialect of Postgres databases.
var SQLite = Dialect{Name: "sqlite", Blob: "BLOB"}
SQLite is the dialect of SQLite databases.
Functions ¶
This section is empty.
Types ¶
type Dialect ¶
Dialect is what differs between the SQL databases a Store supports: the name, the column type of blobs, whether placeholders are numbered ($1) rather than ?, and the statements, if any, that lock the migration and one record in a transaction.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store is a selfhost.Store and selfhost.Ranker in an SQL database: one row per board, period and account in leaderboard_records, with directional ranking indexes for SQL-side Top, Around, Rank and Friends queries, one row per hidden account in leaderboard_hidden, and one per manual reset in leaderboard_resets.
func New ¶
New migrates db's leaderboard schema to SchemaVersion under dialect d and returns a store over it. A schema newer than SchemaVersion is refused.
Example ¶
New migrates a database/sql handle to the leaderboard schema; this example opens a SQLite file in a temporary directory, which a service would replace with SQLite or Postgres of its own.
package main
import (
"context"
"database/sql"
"fmt"
"os"
"path/filepath"
"github.com/nsgo-dev/game/pkg/online/leaderboard/selfhost"
"github.com/nsgo-dev/game/pkg/online/leaderboard/selfhost/sqlstore"
_ "modernc.org/sqlite"
)
func main() {
dir, err := os.MkdirTemp("", "leaderboard")
if err != nil {
fmt.Println(err)
return
}
defer os.RemoveAll(dir)
db, err := sql.Open("sqlite", filepath.Join(dir, "leaderboard.db"))
if err != nil {
fmt.Println(err)
return
}
store, err := sqlstore.New(context.Background(), db, sqlstore.SQLite)
if err != nil {
_ = db.Close()
fmt.Println(err)
return
}
defer store.Close()
store.Configure([]selfhost.Board{{Name: "scores", Order: selfhost.Descending}})
if err := store.Save(context.Background(), selfhost.Record{Board: "scores", Period: "all", Account: "ada", Score: 10}); err != nil {
fmt.Println(err)
return
}
rows, err := store.Records(context.Background(), "scores", "all")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(len(rows), rows[0].Score)
}
Output: 1 10
func (*Store) AccountRecords ¶
func (s *Store) AccountRecords(ctx context.Context, board, period, account string) ([]selfhost.Record, error)
AccountRecords returns account's stored records in board's period, or in every period of board when period is empty.
func (*Store) Around ¶
func (s *Store) Around(ctx context.Context, board selfhost.Board, period, account string, radius int, filter selfhost.RankFilter) ([]selfhost.Entry, int, error)
Around returns account's entry with up to radius entries on each side using keyset index seeks so deep ranks avoid scanning the prefix of the board.
func (*Store) Configure ¶
Configure tells the store each board's order and operator for Store.Save. On a best board Save keeps the better score, the lowest of an ascending board and the highest of any other, with a higher subscore breaking a tie; on a set, increment or decrement board Save stores the record the service computed.
func (*Store) DeleteAccount ¶
DeleteAccount deletes the account's record in board's period, or in every period of board when period is empty.
func (*Store) DeleteHidden ¶
DeleteHidden deletes the hiding of the account on board.
func (*Store) DropPeriod ¶
DropPeriod deletes every record of board in period and returns how many rows were removed.
func (*Store) Friends ¶
func (s *Store) Friends(ctx context.Context, board selfhost.Board, period string, accounts []string, filter selfhost.RankFilter) ([]selfhost.Entry, int, error)
Friends returns the visible entries of accounts in rank order, each carrying its 1-based rank on the whole period. Ranks are computed across disjoint intervals between consecutive friends so the total index scan stays bounded by a single pass.
func (*Store) GetHidden ¶
func (s *Store) GetHidden(ctx context.Context, board, account string) (selfhost.Hidden, bool, error)
GetHidden returns the stored hiding of account on board, whether or not it has lapsed.
func (*Store) Hidden ¶
Hidden returns the active hidden accounts on board at now, sorted by account.
func (*Store) Load ¶
Load calls fn with every stored record, ordered by board, period and account, stopping at fn's first error.
func (*Store) LoadAdmin ¶
LoadAdmin returns the hidden accounts, ordered by board and account, and the manual resets, ordered by board and time.
func (*Store) Periods ¶
Periods returns the distinct (board, period) pairs held by the store, sorted, or only those of board when board is non-empty.
func (*Store) Rank ¶
func (s *Store) Rank(ctx context.Context, board selfhost.Board, period, account string, filter selfhost.RankFilter) (selfhost.Entry, error)
Rank returns account's entry at its 1-based rank in board's period, or selfhost.ErrNotRanked.
func (*Store) Records ¶
Records returns records in deterministic order and is intended for diagnostics and tests.
func (*Store) Save ¶
Save stores rec as one atomic upsert statement. On a best board it leaves the stored record when the account already has a better score in that period, or an equal score with an equal or higher subscore, so concurrent writers keep the best; on any other board it replaces the record.
func (*Store) SaveHidden ¶
SaveHidden stores h, replacing an earlier hiding of the same board and account.
func (*Store) SaveReset ¶
SaveReset stores a manual reset; storing the same board and time again changes nothing.
func (*Store) Submit ¶
func (s *Store) Submit(ctx context.Context, sub selfhost.RankSubmission) (selfhost.RankResult, error)
Submit atomically records sub in sub.Board's sub.Period as a single SQL upsert statement and returns the resulting ranked entry and visible total.