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 is an accounts.Store over database/sql, shared by the SQLite (package sqlitestore) and Postgres (package pgstore) stores. Open a store with one of those; use this package directly only to add another SQL database through a Dialect.
The schema is six tables, created by New when missing and versioned in accounts_schema:
- accounts: id, email (unique, null for none), email_verified, password_hash, created_at, the suspension columns (suspended_at, suspended_until, suspension_reason, suspended_by), and the real-name verification columns (realname_status, realname_birth_year, realname_birth_month, realname_pi, realname_verified_at)
- account_identities: provider and subject (the key), account_id (unique per provider), created_at
- account_sessions: id, account_id, secret_hash, created_at
- account_codes: id, account_id, kind, email, secret_hash, created_at, expires_at
- account_public_profiles: account_id, username (case-insensitively unique), display_name, avatar_url, lang, time_zone, metadata_json, updated_at, username_changed_at
- account_monthly_spend: account_id, month ("YYYY-MM" CST), total_fen
Times are Unix milliseconds. Uniqueness is enforced by the database's constraints, so concurrent services sharing one database cannot give one email address, identity or username to two accounts.
Index ¶
- Constants
- type Dialect
- type Stats
- type Store
- func (s *Store) Account(ctx context.Context, id string) (accounts.Account, error)
- func (s *Store) AccountByEmail(ctx context.Context, email string) (accounts.Account, string, error)
- func (s *Store) AccountByIdentity(ctx context.Context, identity accounts.Identity) (accounts.Account, error)
- func (s *Store) ChangePasswordHash(ctx context.Context, id, passwordHash, keepSession string) error
- func (s *Store) CheckAndRecordSpend(ctx context.Context, id, month string, ...) (int64, error)
- func (s *Store) Close() error
- func (s *Store) Code(ctx context.Context, id string) (accounts.Code, error)
- func (s *Store) CreateAccount(ctx context.Context, a accounts.Account, passwordHash string, ...) error
- func (s *Store) CreateCode(ctx context.Context, c accounts.Code) error
- func (s *Store) CreateSession(ctx context.Context, sess accounts.Session) error
- func (s *Store) DB() *sql.DB
- func (s *Store) DeleteAccount(ctx context.Context, id string) error
- func (s *Store) DeleteCode(ctx context.Context, id string) error
- func (s *Store) DeletePublicProfile(ctx context.Context, accountID string) error
- func (s *Store) DeleteSession(ctx context.Context, id string) error
- func (s *Store) DeleteSessions(ctx context.Context, id string) (int, error)
- func (s *Store) Identities(ctx context.Context, id string) ([]accounts.Identity, error)
- func (s *Store) LinkIdentity(ctx context.Context, id string, identity accounts.Identity, at time.Time) error
- func (s *Store) MonthlySpend(ctx context.Context, id, month string) (int64, error)
- func (s *Store) PublicProfiles(ctx context.Context, ids []string, usernames []string) ([]accounts.PublicProfile, error)
- func (s *Store) RemoveIdentity(ctx context.Context, id, provider string) error
- func (s *Store) ResetPasswordCode(ctx context.Context, id, secretHash, passwordHash string, at time.Time) (string, error)
- func (s *Store) SearchAccounts(ctx context.Context, q accounts.AccountQuery, cursor string, limit int) (accounts.AccountPage, error)
- func (s *Store) Session(ctx context.Context, id string) (accounts.Session, error)
- func (s *Store) Sessions(ctx context.Context, id string) ([]accounts.Session, error)
- func (s *Store) SetEmail(ctx context.Context, id, email, passwordHash string) error
- func (s *Store) SetPasswordHash(ctx context.Context, id, oldHash, newHash string) error
- func (s *Store) SetPublicProfile(ctx context.Context, p accounts.PublicProfile, cooldown time.Duration) (accounts.PublicProfile, error)
- func (s *Store) SetRealName(ctx context.Context, id string, rn *accounts.RealName) error
- func (s *Store) SetSuspension(ctx context.Context, id string, sp *accounts.Suspension) error
- func (s *Store) Stats(ctx context.Context) (Stats, error)
- func (s *Store) UnlinkIdentity(ctx context.Context, id, provider string) error
- func (s *Store) VerifyEmailCode(ctx context.Context, id, secretHash string, at time.Time) (string, error)
Examples ¶
Constants ¶
const SchemaVersion = 5
SchemaVersion is the schema version New creates and accepts. Version 2 added the suspension columns of accounts; version 3 added email_verified and account_codes; version 4 added account_public_profiles; version 5 added the real-name verification columns of accounts and account_monthly_spend. New upgrades version 1, 2, 3 and 4 databases in place.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Dialect ¶
type Dialect struct {
// Name names the database in errors.
Name string
// Numbered is true for "$1" placeholders, false for "?".
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's transaction to serialize migrations of several processes, such as Postgres's pg_advisory_xact_lock.
MigrateLock string
// RowLock is appended to a SELECT of one account in a transaction to lock its row until the transaction ends, such as Postgres's " FOR UPDATE". The store reads the account this way before it checks and changes its credentials and sessions, so that UnlinkIdentity, ChangePasswordHash and CreateSession on one account run one at a time. Leave it empty only for a database whose write transactions already run one at a time, such as SQLite with _txlock=immediate.
RowLock string
}
Dialect is what differs between SQL databases.
type Stats ¶
type Stats struct {
// Accounts is the number of accounts.
Accounts int64
// Sessions is the number of open device sessions: sessions signed in and not yet signed out, replaced or ended with their account.
Sessions int64
}
Stats is how much a store holds, for a service's metrics.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store is an accounts.Store in a SQL database.
func New ¶
New returns a store on db, creating the schema when it is missing. It refuses a database whose schema is newer than SchemaVersion.
Example ¶
New creates the accounts schema on an open database and returns a store on it; a Dialect tells it how the database numbers parameters and reports a unique violation. The sqlitestore and pgstore packages call New with their dialects; this example uses SQLite's, with the driver sqlitestore registers.
package main
import (
"context"
"database/sql"
"fmt"
"github.com/nsgo-dev/game/pkg/online/accounts"
"github.com/nsgo-dev/game/pkg/online/accounts/sqlitestore"
"github.com/nsgo-dev/game/pkg/online/accounts/sqlstore"
)
func main() {
ctx := context.Background()
db, err := sql.Open("sqlite", ":memory:")
if err != nil {
fmt.Println(err)
return
}
// An in-memory SQLite database exists per connection, so keep to one.
db.SetMaxOpenConns(1)
store, err := sqlstore.New(ctx, db, sqlitestore.Dialect)
if err != nil {
fmt.Println(err)
return
}
defer store.Close()
fmt.Println(store.CreateAccount(ctx, accounts.Account{ID: "a1", Email: "ada@example.com"}, ""))
fmt.Println(store.CreateAccount(ctx, accounts.Account{ID: "a2", Email: "ada@example.com"}, ""))
}
Output: <nil> accounts: already belongs to another account
func (*Store) AccountByEmail ¶
AccountByEmail implements accounts.Store.
func (*Store) AccountByIdentity ¶
func (s *Store) AccountByIdentity(ctx context.Context, identity accounts.Identity) (accounts.Account, error)
AccountByIdentity implements accounts.Store.
func (*Store) ChangePasswordHash ¶
ChangePasswordHash implements accounts.Store. It locks the account's row, so a CreateSession of the account waits for it or runs before it.
func (*Store) CheckAndRecordSpend ¶
func (s *Store) CheckAndRecordSpend(ctx context.Context, id, month string, amountFen, perPaymentCapFen, perMonthCapFen int64) (int64, error)
CheckAndRecordSpend implements accounts.RealNameStore. It locks the account row inside the transaction (Dialect.RowLock on Postgres, _txlock=immediate on SQLite) so concurrent purchase requests for the same account cannot bypass monthly spending caps.
func (*Store) CreateAccount ¶
func (s *Store) CreateAccount(ctx context.Context, a accounts.Account, passwordHash string, identities ...accounts.Identity) error
CreateAccount implements accounts.Store.
func (*Store) CreateCode ¶
CreateCode implements accounts.Store.
func (*Store) CreateSession ¶
CreateSession implements accounts.Store. It locks the account's row, so it runs either before a ChangePasswordHash or SetSuspension of the account or after it, never in between.
func (*Store) DeleteAccount ¶
DeleteAccount implements accounts.Store. Foreign-key cascades remove all identities, sessions and codes, and the transaction removes any public profile and frees its username atomically.
func (*Store) DeleteCode ¶
DeleteCode implements accounts.Store.
func (*Store) DeletePublicProfile ¶
DeletePublicProfile implements accounts.PublicProfileStore.
func (*Store) DeleteSession ¶
DeleteSession implements accounts.Store.
func (*Store) DeleteSessions ¶
DeleteSessions implements accounts.Store. It locks the account's row, so a session the account opens at the same time is either deleted or created after it.
func (*Store) Identities ¶
Identities implements accounts.Store.
func (*Store) LinkIdentity ¶
func (s *Store) LinkIdentity(ctx context.Context, id string, identity accounts.Identity, at time.Time) error
LinkIdentity implements accounts.Store.
func (*Store) MonthlySpend ¶
MonthlySpend implements accounts.RealNameStore.
func (*Store) PublicProfiles ¶
func (s *Store) PublicProfiles(ctx context.Context, ids []string, usernames []string) ([]accounts.PublicProfile, error)
PublicProfiles implements accounts.PublicProfileStore.
func (*Store) RemoveIdentity ¶
RemoveIdentity implements accounts.Store.
func (*Store) ResetPasswordCode ¶
func (s *Store) ResetPasswordCode(ctx context.Context, id, secretHash, passwordHash string, at time.Time) (string, error)
ResetPasswordCode implements accounts.Store. It locks the account's row before re-checking the code, replacing the password hash and deleting every session, so a CreateSession or concurrent ResetPasswordCode of the account waits for it or runs before it.
func (*Store) SearchAccounts ¶
func (s *Store) SearchAccounts(ctx context.Context, q accounts.AccountQuery, cursor string, limit int) (accounts.AccountPage, error)
SearchAccounts implements accounts.Store. A prefix is compared with substr rather than LIKE, so '%' and '_' in it match only themselves. Pages are ordered by the database's ordering of IDs, which for the service's lowercase hex IDs is their byte order.
func (*Store) SetPasswordHash ¶
SetPasswordHash implements accounts.Store.
func (*Store) SetPublicProfile ¶
func (s *Store) SetPublicProfile(ctx context.Context, p accounts.PublicProfile, cooldown time.Duration) (accounts.PublicProfile, error)
SetPublicProfile implements accounts.PublicProfileStore. It locks the account's profile row and relies on the unique username constraints, so concurrent claims, renames and cooldown checks are atomic across processes.
func (*Store) SetRealName ¶
SetRealName implements accounts.RealNameStore.
func (*Store) SetSuspension ¶
SetSuspension implements accounts.Store. It locks the account's row, so a CreateSession of the account runs before it or after it.
func (*Store) Stats ¶
Stats counts the store's accounts and sessions. It reads both tables in full, so call it at a scrape's pace, not per request.
func (*Store) UnlinkIdentity ¶
UnlinkIdentity implements accounts.Store. It locks the account's row before it counts the account's credentials, so two unlinks of one account run one at a time and the second sees what the first removed.
func (*Store) VerifyEmailCode ¶
func (s *Store) VerifyEmailCode(ctx context.Context, id, secretHash string, at time.Time) (string, error)
VerifyEmailCode implements accounts.Store. It locks the account's row before re-checking and consuming the code, so concurrent verifications with the same code run one at a time and only the first succeeds.