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: 13 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 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

Examples

Constants

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

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

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

func (s *Store) AccountByFriendCode(ctx context.Context, code string) (string, error)

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

func (s *Store) Block(ctx context.Context, account, other string, now time.Time) error

Block atomically records account->other as StateBlocked and removes any non-block reverse edge.

func (*Store) Blocked

func (s *Store) Blocked(ctx context.Context, a, b string) (bool, error)

Blocked reports whether a blocks b or b blocks a.

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

func (s *Store) Close() error

Close closes the underlying database handle.

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

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

DB returns the underlying database handle.

func (*Store) DeleteGroup

func (s *Store) DeleteGroup(ctx context.Context, id, actor string) error

DeleteGroup removes group id and everything in it for one of its owners, or for server code.

func (*Store) Edge

func (s *Store) Edge(ctx context.Context, account, other string) (social.Edge, bool, error)

Edge returns account's edge toward other, if present.

func (*Store) FriendCode

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

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

func (s *Store) Group(ctx context.Context, id string) (social.Group, error)

Group returns group id.

func (*Store) GroupsOf

func (s *Store) GroupsOf(ctx context.Context, account string) ([]social.Membership, error)

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

func (s *Store) Member(ctx context.Context, id, account string) (social.GroupMember, bool, error)

Member returns account's role in group id.

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

func (s *Store) RemoveFriend(ctx context.Context, account, other string) (bool, error)

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.

func (*Store) Unblock

func (s *Store) Unblock(ctx context.Context, account, other string) (bool, error)

Unblock removes account's block on other without touching any block other holds on account.

func (*Store) UpdateGroup

func (s *Store) UpdateGroup(ctx context.Context, id, actor string, u social.GroupUpdate) (social.Group, error)

UpdateGroup applies u to group id for one of its owners or admins, or for server code.

Jump to

Keyboard shortcuts

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