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 social friend/invite/block edges and friend codes in a SQL database over database/sql, shared by the SQLite (package sqlitestore) and Postgres (package pgstore) stores.
The schema is five tables, created by New when missing and versioned in social_schema:
- social_schema: version
- social_edges: (account, other) primary key, state, updated_at (Unix ms UTC), indexed on (account, state, other)
- social_friend_codes: account primary key, code (unique), created_at (Unix ms UTC)
- social_groups (version 2): id primary key, name, name_key (unique, social.GroupNameKey), description, avatar_url, lang, is_open (0 or 1), max_members, member_count, metadata (JSON text), created_at (Unix ms UTC)
- social_group_members (version 2): (group_id, account) primary key, role, updated_at (Unix ms UTC), indexed on (account, group_id) and (group_id, role, account)
Each relationship pair is stored as two directed rows (account->other and other->account) and updated atomically inside one database transaction. Each group call runs in one transaction too, and New upgrades a version 1 database by adding the group tables.
Index ¶
- Constants
- type Dialect
- type Store
- func (s *Store) AccountByFriendCode(ctx context.Context, code string) (string, error)
- func (s *Store) AddFriend(ctx context.Context, account, other string, limits social.AddLimits, ...) (social.AddResult, error)
- func (s *Store) Block(ctx context.Context, account, other string, now time.Time) error
- func (s *Store) Blocked(ctx context.Context, a, b string) (bool, error)
- func (s *Store) ChangeMember(ctx context.Context, ch social.MemberChange, maxGroupsPerAccount int, ...) (social.Role, social.Role, error)
- func (s *Store) Close() error
- func (s *Store) CreateGroup(ctx context.Context, g social.Group, owner string, maxGroupsPerAccount int) (social.Group, error)
- func (s *Store) DB() *sql.DB
- func (s *Store) DeleteGroup(ctx context.Context, id, actor string) error
- func (s *Store) Edge(ctx context.Context, account, other string) (social.Edge, bool, error)
- func (s *Store) FriendCode(ctx context.Context, account string) (string, error)
- func (s *Store) Friends(ctx context.Context, account string, state social.EdgeState, cursor string, ...) (social.EdgePage, error)
- func (s *Store) Group(ctx context.Context, id string) (social.Group, error)
- func (s *Store) GroupsOf(ctx context.Context, account string) ([]social.Membership, error)
- func (s *Store) ListGroups(ctx context.Context, f social.GroupFilter, cursor string, limit int) (social.GroupPage, error)
- func (s *Store) Member(ctx context.Context, id, account string) (social.GroupMember, bool, error)
- func (s *Store) Members(ctx context.Context, id string, role social.Role, cursor string, limit int) (social.MemberPage, error)
- func (s *Store) RemoveFriend(ctx context.Context, account, other string) (bool, error)
- func (s *Store) SetFriendCode(ctx context.Context, account, code string, now time.Time) (string, error)
- func (s *Store) Unblock(ctx context.Context, account, other string) (bool, error)
- func (s *Store) UpdateGroup(ctx context.Context, id, actor string, u social.GroupUpdate) (social.Group, error)
Examples ¶
Constants ¶
const SchemaVersion = 2
SchemaVersion is the schema version New creates and accepts. Databases with a newer schema version are refused.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Dialect ¶
type Dialect struct {
// Name names the database in error messages.
Name string
// Numbered is true for "$1" placeholders (Postgres) and false for "?" (SQLite).
Numbered bool
// IsUnique reports whether err is a unique or primary key constraint violation.
IsUnique func(err error) bool
// MigrateLock, when set, runs first in the migration transaction to serialize concurrent migrations.
MigrateLock string
// LockKey, when set, runs inside write transactions with one int64 lock key per touched account,
// in strictly ascending key order, to serialize concurrent writes across processes without deadlock.
LockKey string
// Collate, when set, is appended to text comparisons and ORDER BY clauses on other so cursor
// pagination uses byte order regardless of the database locale (for example ` COLLATE "C"` on Postgres).
Collate string
}
Dialect describes what differs between SQL databases supported by Store.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store is a social.Store backed by a SQL database.
func New ¶
New migrates db to SchemaVersion under dialect d and returns a Store over it. A database with a schema version newer than SchemaVersion is refused.
Example ¶
New migrates a database/sql handle to the social schema and stores mutual friend edges in one transaction.
package main
import (
"context"
"database/sql"
"errors"
"fmt"
"os"
"path/filepath"
"time"
"modernc.org/sqlite"
"github.com/nsgo-dev/game/pkg/online/social"
"github.com/nsgo-dev/game/pkg/online/social/sqlstore"
)
func main() {
dir, err := os.MkdirTemp("", "social-sqlstore")
if err != nil {
fmt.Println(err)
return
}
defer os.RemoveAll(dir)
db, err := sql.Open("sqlite", filepath.Join(dir, "social.db")+"?_txlock=immediate")
if err != nil {
fmt.Println(err)
return
}
db.SetMaxOpenConns(1)
dialect := sqlstore.Dialect{
Name: "sqlite",
IsUnique: func(err error) bool {
var e *sqlite.Error
return errors.As(err, &e) && (e.Code() == 1555 || e.Code() == 2067)
},
}
store, err := sqlstore.New(context.Background(), db, dialect)
if err != nil {
_ = db.Close()
fmt.Println(err)
return
}
defer store.Close()
now := time.Date(2026, 12, 2, 0, 0, 0, 0, time.UTC)
_, _ = store.AddFriend(context.Background(), "ana", "ben", social.AddLimits{MaxFriends: 100}, now)
res, _ := store.AddFriend(context.Background(), "ben", "ana", social.AddLimits{MaxFriends: 100}, now)
page, _ := store.Friends(context.Background(), "ana", social.StateFriend, "", 10)
fmt.Println(res, len(page.Edges), page.Edges[0].Other)
}
Output: accepted 1 ben
func (*Store) AccountByFriendCode ¶
AccountByFriendCode returns the account owning code, or social.ErrNotFound.
func (*Store) AddFriend ¶
func (s *Store) AddFriend(ctx context.Context, account, other string, limits social.AddLimits, now time.Time) (social.AddResult, error)
AddFriend atomically invites other on account's behalf or promotes a received invite into mutual StateFriend.
func (*Store) Block ¶
Block atomically records account->other as StateBlocked and removes any non-block reverse edge.
func (*Store) ChangeMember ¶
func (s *Store) ChangeMember(ctx context.Context, ch social.MemberChange, maxGroupsPerAccount int, now time.Time) (social.Role, social.Role, error)
ChangeMember applies ch through social.DecideMember in one transaction.
func (*Store) CreateGroup ¶
func (s *Store) CreateGroup(ctx context.Context, g social.Group, owner string, maxGroupsPerAccount int) (social.Group, error)
CreateGroup stores g with owner as its only owner.
func (*Store) DeleteGroup ¶
DeleteGroup removes group id and everything in it for one of its owners, or for server code.
func (*Store) FriendCode ¶
FriendCode returns account's assigned friend code, or social.ErrNotFound.
func (*Store) Friends ¶
func (s *Store) Friends(ctx context.Context, account string, state social.EdgeState, cursor string, limit int) (social.EdgePage, error)
Friends returns up to limit edges of account matching state with Other strictly greater than cursor, ordered by Other ascending in byte order.
func (*Store) GroupsOf ¶
GroupsOf returns the groups account belongs to or has requested, ordered by group ID.
func (*Store) ListGroups ¶
func (s *Store) ListGroups(ctx context.Context, f social.GroupFilter, cursor string, limit int) (social.GroupPage, error)
ListGroups returns a page of groups matching f, ordered by name key in byte order.
func (*Store) Members ¶
func (s *Store) Members(ctx context.Context, id string, role social.Role, cursor string, limit int) (social.MemberPage, error)
Members returns a page of group id's accounts holding role, ordered by account in byte order.
func (*Store) RemoveFriend ¶
RemoveFriend atomically removes a friendship or pending invitation on both sides without lifting blocks.
func (*Store) SetFriendCode ¶
func (s *Store) SetFriendCode(ctx context.Context, account, code string, now time.Time) (string, error)
SetFriendCode atomically stores code for account if account does not already have one.