sqlstore

package
v0.4.0-rc.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 11 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

Examples

Constants

View Source
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

View Source
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.

View Source
var SQLite = Dialect{Name: "sqlite", Blob: "BLOB"}

SQLite is the dialect of SQLite databases.

Functions

This section is empty.

Types

type Dialect

type Dialect struct {
	Name, Blob              string
	Numbered                bool
	MigrateLock, LockRecord string
}

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

func New(ctx context.Context, db *sql.DB, d Dialect) (*Store, error)

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) Close

func (s *Store) Close() error

Close closes the store's database.

func (*Store) Configure

func (s *Store) Configure(boards []selfhost.Board)

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) DB

func (s *Store) DB() *sql.DB

DB returns the store's database.

func (*Store) DeleteAccount

func (s *Store) DeleteAccount(ctx context.Context, board, period, account string) error

DeleteAccount deletes the account's record in board's period, or in every period of board when period is empty.

func (*Store) DeleteHidden

func (s *Store) DeleteHidden(ctx context.Context, board, account string) error

DeleteHidden deletes the hiding of the account on board.

func (*Store) Drop

func (s *Store) Drop(ctx context.Context, board, period string) error

Drop deletes every record of board in period.

func (*Store) DropPeriod

func (s *Store) DropPeriod(ctx context.Context, board, period string) (int, error)

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

func (s *Store) Hidden(ctx context.Context, board string, now time.Time) ([]selfhost.Hidden, error)

Hidden returns the active hidden accounts on board at now, sorted by account.

func (*Store) Load

func (s *Store) Load(ctx context.Context, fn func(selfhost.Record) error) error

Load calls fn with every stored record, ordered by board, period and account, stopping at fn's first error.

func (*Store) LoadAdmin

func (s *Store) LoadAdmin(ctx context.Context) (selfhost.AdminState, error)

LoadAdmin returns the hidden accounts, ordered by board and account, and the manual resets, ordered by board and time.

func (*Store) Periods

func (s *Store) Periods(ctx context.Context, board string) ([][2]string, error)

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

func (s *Store) Records(ctx context.Context, board, period string) ([]selfhost.Record, error)

Records returns records in deterministic order and is intended for diagnostics and tests.

func (*Store) Resets

func (s *Store) Resets(ctx context.Context, board string) ([]time.Time, error)

Resets returns the manual reset timestamps of board, ascending.

func (*Store) Save

func (s *Store) Save(ctx context.Context, rec selfhost.Record) error

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

func (s *Store) SaveHidden(ctx context.Context, h selfhost.Hidden) error

SaveHidden stores h, replacing an earlier hiding of the same board and account.

func (*Store) SaveReset

func (s *Store) SaveReset(ctx context.Context, r selfhost.BoardReset) error

SaveReset stores a manual reset; storing the same board and time again changes nothing.

func (*Store) Submit

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.

func (*Store) Top

func (s *Store) Top(ctx context.Context, board selfhost.Board, period string, offset, limit int, filter selfhost.RankFilter) ([]selfhost.Entry, int, error)

Top returns up to limit entries from 1-based rank offset+1 onward in rank order.

func (*Store) Total

func (s *Store) Total(ctx context.Context, board selfhost.Board, period string, filter selfhost.RankFilter) (int, error)

Total returns the number of visible entries in board's period.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL