Multiplayer Game Backend ER diagram and database schema

The Multiplayer Game Backend database schema is a DB Planner template with 30 tables, 245 columns and 67 relationships, free to use. Core tables include achievements, currencies, friendships, game_modes. It can be opened as an interactive ER diagram or exported as PostgreSQL, MySQL, or SQL Server DDL.

ER diagram of the Multiplayer Game Backend database schema, showing 30 tables and their relationships
FIG. 1: entity relationship diagram, 30 tables
Tables
30
Columns
245
Relationships
67
Category
Gaming
Exports
DBML, SQL, Prisma, C#
Price
Free

What this schema models

A complete multiplayer game backend database design, built the way live-service games protect their economies and ranked ladders: 30 tables, 19 enums and 67 relationships covering player accounts with linked platform identities, a currency wallet ledger, items and inventory, store offers and receipt-validated purchases, seasons, game modes, matchmaking tickets and match results, append-only rating history and leaderboard snapshots, achievements, friends, parties and guilds, and player reports and sanctions. THE FOUR DESIGN RULES 1. A wallet is a ledger, never a balance column. Every credit and debit of every currency is an insert into wallet_ledger_entries with its cause (purchase, match reward, store spend, admin adjustment) and a running balance_after computed under a row lock. There is no balance to UPDATE, so a duplication exploit shows up as rows with a reason, and any balance can be rebuilt from history. 2. Every grant is idempotent. A purchase is unique on (platform, platform transaction id), so a resent receipt returns the existing purchase; every ledger entry carries a unique idempotency key, so a retried fulfilment or reward collides instead of paying twice. 3. Ratings are append-only. rating_events records MMR before and after, per player, per mode, per season; player_ratings is only a cache of the latest row. Undoing the games lost to a banned cheater is a correction row, never an edit. 4. One game account, many platforms. players is independent of any storefront or console network; platform_identities links each external account to exactly one player at a time, which is what makes cross-progression work. Platforms are data, so supporting a new storefront is an INSERT. DETAILS WORTH STEALING - Friendships are stored once as an ordered pair (player_low_id < player_high_id), so A-B and B-A can never both exist. - Leaderboards are snapshots: readers page a frozen board instead of sorting a live table, and the final snapshot is the one season rewards are paid from. - Inventory items record what granted them (purchase, match, achievement), and a refund or chargeback sets revoked_at instead of deleting the row. - Sanctions are rows with a time window (warnings, chat mutes, queue cooldowns, ranked bans, account bans); players.status only caches what is active. - Admin currency adjustments must name a staff account, so an insider grant is always attributed. - Matches record the server build, so every match played on a buggy build can be found and invalidated; an invalidated match pays no rewards and moves no ratings. WHAT YOU GET Clean DBML that imports directly into DB Planner, and a laid-out board with zones color-coded and framed: players and identity, social, matchmaking and matches, ratings and progression, economy and store, and moderation. Every table carries a note. Postgres types throughout; the two jsonb columns (matchmaking latency samples and per-match player stats) map to JSON in MySQL or NVARCHAR(MAX) in SQL Server. Useful for developers building the backend for an online multiplayer game, and for students who need a realistic multiplayer game ER diagram for a DBMS project. This is a schema design reference; anti-cheat, rating math and platform store rules belong in your own services.

Tables (30)

Every table and its columns

platforms

Storefronts, console networks and mobile app stores the game ships on. Platforms are data, not schema, so adding one is an INSERT.

Columns of the platforms table
ColumnTypeConstraintsReferencesDescription
iduuidPK
codevarchar(30)unique, not nullYour own short code per integration, e.g. pc_store_a, console_b, mobile_store_a
namevarchar(100)not null
kindplatform_kindnot null
has_storebooleannot null, default trueWhether purchases can arrive with a receipt from this platform

players

The game account, independent of any platform. Wallet, inventory and ratings hang off this id, which is what makes cross-progression possible.

Columns of the players table
ColumnTypeConstraintsReferencesDescription
iduuidPK
display_namevarchar(32)not null
name_tagchar(4)not nullFour-digit suffix, so display names need not be unique: "Raven#4821"
countrychar(2)
statusaccount_statusnot null, default 'active'CACHE of active sanctions, refreshed when one starts, expires or is revoked
created_attimestamptznot null, default `now()`
last_login_attimestamptz
deleted_attimestamptzSoft delete for data-deletion requests. Ledger rows stay, keyed by an id that no longer identifies anyone

Indexes: (display_name, name_tag) unique

platform_identities

Linked platform accounts. Sign-in looks up (platform, external id) to find the player; a player on three platforms has three rows.

Columns of the platform_identities table
ColumnTypeConstraintsReferencesDescription
iduuidPK
player_iduuidFK, not nullplayers.id
platform_iduuidFK, not nullplatforms.id
external_user_idvarchar(128)not nullThe account id the platform hands over after sign-in
external_display_namevarchar(100)
linked_attimestamptznot null, default `now()`
last_auth_attimestamptz
unlinked_attimestamptz

Indexes: (platform_id, external_user_id), (player_id)

player_profiles

What other players see: equipped cosmetics, title and level. Split from players so a busy profile never locks the account row.

Columns of the player_profiles table
ColumnTypeConstraintsReferencesDescription
player_iduuidPK, FKplayers.id
avatar_item_iduuidFKitems.idAn equipped cosmetic must be owned: checked against inventory on equip
banner_item_iduuidFKitems.id
title_achievement_iduuidFKachievements.idA display title unlocked by an achievement
account_levelintegernot null, default 1
account_xpbigintnot null, default 0
show_online_statusbooleannot null, default true
updated_attimestamptznot null, default `now()`

currencies

Virtual currencies. Premium currency is bought, so it carries refund and chargeback obligations that soft currency does not.

Columns of the currencies table
ColumnTypeConstraintsReferencesDescription
iduuidPK
codevarchar(10)unique, not nulle.g. GOLD (soft), GEMS (premium)
namevarchar(60)not null
kindcurrency_kindnot null
max_balancebigintCap enforced when a credit is written; null for no cap
is_purchasablebooleannot null, default falseOnly premium currency is sold for real money

wallet_ledger_entries

The wallet. There is no balance column anywhere to UPDATE: every change to every currency is an insert here, with its cause. A duplication exploit shows up as rows with a reason, and any balance can be recomputed from history.

Columns of the wallet_ledger_entries table
ColumnTypeConstraintsReferencesDescription
iduuidPK
player_iduuidFK, not nullplayers.id
currency_iduuidFK, not nullcurrencies.id
sequencebigintnot nullPer player and currency: 1, 2, 3 with no gaps
amountbigintnot nullSigned: a credit is positive, a debit negative. Never zero
balance_afterbigintnot nullRunning balance, computed at insert from the previous row (locked FOR UPDATE). A CHECK keeps it at or above zero
reasonledger_reasonnot null
purchase_iduuidFKpurchases.id
match_iduuidFKmatches.id
achievement_iduuidFKachievements.id
staff_account_iduuidFKstaff_accounts.idRequired for admin adjustments, so an insider grant is always attributed
idempotency_keyvarchar(100)unique, not nulle.g. purchase:<id>:credit or match:<id>:reward. A retried grant collides here instead of paying twice
created_attimestamptznot null, default `now()`

Indexes: (player_id, currency_id, sequence) unique

items

The item catalog: everything a player can own.

Columns of the items table
ColumnTypeConstraintsReferencesDescription
iduuidPK
skuvarchar(60)unique, not null
namevarchar(120)not null
kinditem_kindnot null
rarityitem_raritynot null
is_stackablebooleannot null, default falseConsumables stack into one inventory row with a quantity
is_tradeablebooleannot null, default false
released_attimestamptz
retired_attimestamptzNo longer obtainable. Owned copies are kept

inventory_items

Item instances a player owns, each pointing at whatever granted it. Revoking is a timestamp, so support can always answer "where did this come from?"

Columns of the inventory_items table
ColumnTypeConstraintsReferencesDescription
iduuidPK
player_iduuidFK, not nullplayers.id
item_iduuidFK, not nullitems.id
quantityintegernot null, default 1Remaining uses for stackable consumables; 1 for everything else
grant_reasongrant_reasonnot null
purchase_iduuidFKpurchases.id
match_iduuidFKmatches.id
achievement_iduuidFKachievements.id
granted_attimestamptznot null, default `now()`
expires_attimestamptzRentals and time-limited boosts
revoked_attimestamptzSet by a refund or chargeback. The row stays as evidence

Indexes: (player_id, item_id)

store_offers

What the in-game store sells: a bundle of contents for one price, in real money or a virtual currency.

Columns of the store_offers table
ColumnTypeConstraintsReferencesDescription
iduuidPK
skuvarchar(60)unique, not null
namevarchar(120)not null
price_kindoffer_price_kindnot null
price_currency_iduuidFKcurrencies.idSet when priced in a virtual currency
price_amountbigintIn units of price_currency_id
platform_product_idvarchar(100)Set when priced in real money: the product id configured in each platform store. Real prices live in the store, not here
starts_attimestamptz
ends_attimestamptzLimited-time offers
max_per_playerintegere.g. 1 for a starter pack
is_activebooleannot null, default true

offer_contents

What an offer grants. Exactly one of item_id and currency_id per row, so a gem pack is just an offer whose only content is currency.

Columns of the offer_contents table
ColumnTypeConstraintsReferences
iduuidPK
store_offer_iduuidFK, not nullstore_offers.id
item_iduuidFKitems.id
currency_iduuidFKcurrencies.id
quantitybigintnot null

purchases

Every purchase, as a state machine: validate the receipt server-side with the platform, then fulfil by writing ledger and inventory rows keyed on this id. Never trust a client that says it paid.

Columns of the purchases table
ColumnTypeConstraintsReferencesDescription
iduuidPK
player_iduuidFK, not nullplayers.id
store_offer_iduuidFK, not nullstore_offers.id
platform_iduuidFKplatforms.idNull for purchases paid in virtual currency
platform_transaction_idvarchar(200)The receipt or order id issued by the platform store
receipt_payloadtextRaw receipt as received, kept for disputes and re-validation
statuspurchase_statusnot null, default 'pending_validation'
price_centsintegerReal-money amount as reported by the store
currencychar(3)
created_attimestamptznot null, default `now()`
validated_attimestamptz
fulfilled_attimestamptz
refunded_attimestamptz

Indexes: (platform_id, platform_transaction_id) unique, (player_id, created_at)

seasons

Competitive seasons. Ratings and leaderboards are scoped to one.

Columns of the seasons table
ColumnTypeConstraintsReferencesDescription
iduuidPK
numberintegerunique, not null
namevarchar(100)not null
starts_attimestamptznot null
ends_attimestamptznot null
soft_reset_factornumeric(3,2)not null, default 0.5How far ratings are pulled toward the mean at season start

game_modes

Playlists. A rating only means something within one mode, so ratings are keyed by it.

Columns of the game_modes table
ColumnTypeConstraintsReferencesDescription
iduuidPK
codevarchar(30)unique, not nulle.g. ranked_5v5, casual_ffa
namevarchar(100)not null
team_countsmallintnot null
team_sizesmallintnot null
is_rankedbooleannot null, default false
is_activebooleannot null, default true

matchmaking_tickets

A request to play. Kept after matching, so time-to-match and abandoned queues can be measured.

Columns of the matchmaking_tickets table
ColumnTypeConstraintsReferencesDescription
iduuidPK
player_iduuidFK, not nullplayers.idThe player who queued; for a party, its leader
party_iduuidFKparties.id
game_mode_iduuidFK, not nullgame_modes.id
regionvarchar(20)not nulle.g. eu-west, us-east
rating_at_queueintegernot nullSnapshot used for matching; a party queues on a combined rating
latency_msjsonbMeasured ping per region, e.g. {"eu-west": 31, "us-east": 104}
statusticket_statusnot null, default 'queued'
created_attimestamptznot null, default `now()`
matched_attimestamptz
match_iduuidFKmatches.id

Indexes: (game_mode_id, region, status, created_at)

matches

One played game, with results written by the authoritative server, never by a client. An invalidated match keeps its row but pays no rewards and moves no ratings.

Columns of the matches table
ColumnTypeConstraintsReferencesDescription
iduuidPK
game_mode_iduuidFK, not nullgame_modes.id
season_iduuidFKseasons.id
regionvarchar(20)not null
server_idvarchar(100)Allocated dedicated server or session host
server_buildvarchar(40)Game server version, for when a bug invalidates every match played on one build
statusmatch_statusnot null, default 'allocating'
started_attimestamptz
ended_attimestamptz
winning_teamsmallint

match_participants

Who played, on which team, and how it went for them. Rewards and rating changes are computed from these rows.

Columns of the match_participants table
ColumnTypeConstraintsReferencesDescription
match_iduuidFK, not nullmatches.id
player_iduuidFK, not nullplayers.id
teamsmallintnot null
party_iduuidFKparties.id
outcomematch_outcome
placementsmallintFinishing position, for free-for-all modes
scoreinteger
statsjsonbMode-specific numbers, e.g. kills, assists, objectives
joined_attimestamptznot null
left_attimestamptzEarlier than the match end means the player left early

Indexes: (player_id, joined_at)

rating_events

Append-only MMR history per player, per mode, per season. Undoing the games lost to a banned cheater is a new correction row, never an edit.

Columns of the rating_events table
ColumnTypeConstraintsReferencesDescription
iduuidPK
player_iduuidFK, not nullplayers.id
game_mode_iduuidFK, not nullgame_modes.id
season_iduuidFK, not nullseasons.id
match_iduuidFKmatches.idNull for season resets and decay
kindrating_event_kindnot null
rating_beforeintegernot null
rating_afterintegernot null
uncertainty_afternumeric(6,2)Rating deviation, for systems that track confidence as well as skill
created_attimestamptznot null, default `now()`

Indexes: (player_id, game_mode_id, season_id, created_at), (player_id, match_id, kind) unique

player_ratings

CACHE of the latest rating_events row, for the matchmaker and the profile. Rebuildable from history at any time.

Columns of the player_ratings table
ColumnTypeConstraintsReferencesDescription
player_iduuidFK, not nullplayers.id
game_mode_iduuidFK, not nullgame_modes.id
season_iduuidFK, not nullseasons.id
ratingintegernot null
uncertaintynumeric(6,2)
games_playedintegernot null, default 0
winsintegernot null, default 0
last_rating_event_iduuidFK, not nullrating_events.idThe event this cache was built from
updated_attimestamptznot null

Indexes: (game_mode_id, season_id, rating)

leaderboard_snapshots

A leaderboard frozen at a moment, e.g. every 15 minutes. Readers page through a snapshot instead of sorting a live table, and the final one is the permanent record.

Columns of the leaderboard_snapshots table
ColumnTypeConstraintsReferencesDescription
iduuidPK
game_mode_iduuidFK, not nullgame_modes.id
season_iduuidFK, not nullseasons.id
regionvarchar(20)Null for the global board
taken_attimestamptznot null
is_finalbooleannot null, default falseThe end-of-season board that season rewards are paid from

leaderboard_entries

The ranked rows of a snapshot. Usually only the top few thousand are stored.

Columns of the leaderboard_entries table
ColumnTypeConstraintsReferencesDescription
snapshot_iduuidFK, not nullleaderboard_snapshots.id
rankintegernot nullTies broken by who reached the rating first
player_iduuidFK, not nullplayers.id
ratingintegernot null
display_namevarchar(40)not nullCopied at snapshot time, so the board reads without a join and shows the name used then

Indexes: (snapshot_id, player_id) unique

achievements

Achievement definitions and what they pay out.

Columns of the achievements table
ColumnTypeConstraintsReferencesDescription
iduuidPK
codevarchar(60)unique, not null
namevarchar(120)not null
descriptionvarchar(500)not null
target_valueintegernot null, default 1e.g. 100 for "win 100 ranked matches"
is_hiddenbooleannot null, default falseSecret until unlocked
reward_item_iduuidFKitems.id
reward_currency_iduuidFKcurrencies.id
reward_amountbigint

player_achievements

Progress toward each achievement, created on first progress.

Columns of the player_achievements table
ColumnTypeConstraintsReferencesDescription
player_iduuidFK, not nullplayers.id
achievement_iduuidFK, not nullachievements.id
progressintegernot null, default 0
completed_attimestamptz
reward_claimed_attimestamptzClaiming writes the ledger or inventory row; its idempotency key stops a double claim
updated_attimestamptznot null

friendships

Mutual friendships stored once, as an ordered pair, so A-B and B-A can never both exist. A friends list reads both columns.

Columns of the friendships table
ColumnTypeConstraintsReferencesDescription
player_low_iduuidFK, not nullplayers.idThe smaller of the two ids (CHECK player_low_id < player_high_id)
player_high_iduuidFK, not nullplayers.id
requested_byuuidFK, not nullplayers.id
statusfriendship_statusnot null, default 'pending'
created_attimestamptznot null, default `now()`
accepted_attimestamptz

Indexes: (player_high_id)

parties

A group that queues together. Short-lived, but kept for match history and for spotting win-trading groups.

Columns of the parties table
ColumnTypeConstraintsReferencesDescription
iduuidPK
leader_iduuidFK, not nullplayers.id
game_mode_iduuidFKgame_modes.idWhat the party is about to queue for
max_sizesmallintnot null
invite_codevarchar(12)unique
created_attimestamptznot null, default `now()`
disbanded_attimestamptz

party_members

Who is, or was, in a party.

Columns of the party_members table
ColumnTypeConstraintsReferences
party_iduuidFK, not nullparties.id
player_iduuidFK, not nullplayers.id
joined_attimestamptznot null, default `now()`
left_attimestamptz

Indexes: (player_id)

guilds

Long-lived player organizations: guilds, clans, crews.

Columns of the guilds table
ColumnTypeConstraintsReferencesDescription
iduuidPK
namevarchar(50)unique, not null
tagvarchar(5)unique, not nullShort tag shown beside member names, e.g. [ABC]
descriptionvarchar(500)
member_limitsmallintnot null, default 50
is_openbooleannot null, default falseOpen guilds accept joins without an invite
created_attimestamptznot null, default `now()`
disbanded_attimestamptz

guild_members

Membership history with roles. Leadership is a role, not a column on guilds, so a handover is two updates in one transaction.

Columns of the guild_members table
ColumnTypeConstraintsReferences
iduuidPK
guild_iduuidFK, not nullguilds.id
player_iduuidFK, not nullplayers.id
roleguild_rolenot null, default 'member'
joined_attimestamptznot null, default `now()`
left_attimestamptz
left_reasonguild_leave_reason

Indexes: (player_id), (guild_id, role)

staff_accounts

Support agents, moderators and live-ops staff. Kept apart from players: staff never act through a game account.

Columns of the staff_accounts table
ColumnTypeConstraintsReferences
iduuidPK
emailvarchar(254)unique, not null
namevarchar(120)not null
rolestaff_rolenot null
disabled_attimestamptz

player_reports

In-game reports. Volume per reported player feeds automated review; one report rarely decides anything alone.

Columns of the player_reports table
ColumnTypeConstraintsReferencesDescription
iduuidPK
reporter_iduuidFK, not nullplayers.id
reported_player_iduuidFK, not nullplayers.id
match_iduuidFKmatches.idThe match it happened in, so a reviewer can pull the replay
reasonreport_reasonnot null
detailsvarchar(1000)
created_attimestamptznot null, default `now()`
reviewed_attimestamptz
reviewed_byuuidFKstaff_accounts.id
sanction_iduuidFKsanctions.idThe sanction it led to, if any

Indexes: (reported_player_id, created_at)

sanctions

Warnings, chat mutes, queue cooldowns, ranked bans and account bans, each a row with a time window. A ban is a sanction, so its history and appeal live in one place; players.status only caches what is active.

Columns of the sanctions table
ColumnTypeConstraintsReferencesDescription
iduuidPK
player_iduuidFK, not nullplayers.id
kindsanction_kindnot null
reasonreport_reasonnot null
detailstext
issued_byuuidFKstaff_accounts.idNull for automated systems such as anti-cheat
evidence_match_iduuidFKmatches.id
starts_attimestamptznot null, default `now()`
expires_attimestamptzNull for permanent
revoked_attimestamptzOverturned on appeal. The row stays
revoked_byuuidFKstaff_accounts.id
created_attimestamptznot null, default `now()`

Indexes: (player_id, expires_at)

Enums (19)

platform_kind
pc, console, mobile, web
account_status
active, suspended, banned, deleted
currency_kind
soft, premium, event
ledger_reason
purchase_credit, store_spend, match_reward, achievement_reward, season_reward, refund_reversal, chargeback_reversal, admin_adjustment, expiry
item_kind
character, skin, weapon, emote, avatar, banner, consumable, boost
item_rarity
common, uncommon, rare, epic, legendary
grant_reason
purchase, match_reward, achievement, season_reward, starter, admin_grant
offer_price_kind
real_money, virtual_currency
purchase_status
pending_validation, validated, fulfilled, rejected, refunded, chargeback
ticket_status
queued, matched, cancelled, timed_out
match_status
allocating, in_progress, completed, abandoned, invalidated
match_outcome
win, loss, draw, abandoned
rating_event_kind
match, season_reset, decay, correction
friendship_status
pending, accepted
guild_role
leader, officer, member, recruit
guild_leave_reason
left, kicked, guild_disbanded
staff_role
support, moderator, live_ops, admin
report_reason
cheating, griefing, abusive_chat, offensive_name, win_trading, account_sharing, other
sanction_kind
warning, chat_mute, matchmaking_cooldown, ranked_ban, temporary_ban, permanent_ban

Relationships (67)

  • achievements.reward_currency_id references currencies.id many to one
  • achievements.reward_item_id references items.id many to one
  • friendships.player_high_id references players.id many to one
  • friendships.player_low_id references players.id many to one
  • friendships.requested_by references players.id many to one
  • guild_members.guild_id references guilds.id many to one
  • guild_members.player_id references players.id many to one
  • inventory_items.achievement_id references achievements.id many to one
  • inventory_items.item_id references items.id many to one
  • inventory_items.match_id references matches.id many to one
  • inventory_items.player_id references players.id many to one
  • inventory_items.purchase_id references purchases.id many to one
  • leaderboard_entries.player_id references players.id many to one
  • leaderboard_entries.snapshot_id references leaderboard_snapshots.id many to one
  • leaderboard_snapshots.game_mode_id references game_modes.id many to one
  • leaderboard_snapshots.season_id references seasons.id many to one
  • match_participants.match_id references matches.id many to one
  • match_participants.party_id references parties.id many to one
  • match_participants.player_id references players.id many to one
  • matches.game_mode_id references game_modes.id many to one
  • matches.season_id references seasons.id many to one
  • matchmaking_tickets.game_mode_id references game_modes.id many to one
  • matchmaking_tickets.match_id references matches.id many to one
  • matchmaking_tickets.party_id references parties.id many to one
  • matchmaking_tickets.player_id references players.id many to one
  • offer_contents.currency_id references currencies.id many to one
  • offer_contents.item_id references items.id many to one
  • offer_contents.store_offer_id references store_offers.id many to one
  • parties.game_mode_id references game_modes.id many to one
  • parties.leader_id references players.id many to one
  • party_members.party_id references parties.id many to one
  • party_members.player_id references players.id many to one
  • platform_identities.platform_id references platforms.id many to one
  • platform_identities.player_id references players.id many to one
  • player_achievements.achievement_id references achievements.id many to one
  • player_achievements.player_id references players.id many to one
  • player_profiles.avatar_item_id references items.id many to one
  • player_profiles.banner_item_id references items.id many to one
  • player_profiles.title_achievement_id references achievements.id many to one
  • player_ratings.game_mode_id references game_modes.id many to one
  • player_ratings.last_rating_event_id references rating_events.id many to one
  • player_ratings.player_id references players.id many to one
  • player_ratings.season_id references seasons.id many to one
  • player_reports.match_id references matches.id many to one
  • player_reports.reported_player_id references players.id many to one
  • player_reports.reporter_id references players.id many to one
  • player_reports.reviewed_by references staff_accounts.id many to one
  • player_reports.sanction_id references sanctions.id many to one
  • players.id references player_profiles.player_id one to one
  • purchases.platform_id references platforms.id many to one
  • purchases.player_id references players.id many to one
  • purchases.store_offer_id references store_offers.id many to one
  • rating_events.game_mode_id references game_modes.id many to one
  • rating_events.match_id references matches.id many to one
  • rating_events.player_id references players.id many to one
  • rating_events.season_id references seasons.id many to one
  • sanctions.evidence_match_id references matches.id many to one
  • sanctions.issued_by references staff_accounts.id many to one
  • sanctions.player_id references players.id many to one
  • sanctions.revoked_by references staff_accounts.id many to one
  • store_offers.price_currency_id references currencies.id many to one
  • wallet_ledger_entries.achievement_id references achievements.id many to one
  • wallet_ledger_entries.currency_id references currencies.id many to one
  • wallet_ledger_entries.match_id references matches.id many to one
  • wallet_ledger_entries.player_id references players.id many to one
  • wallet_ledger_entries.purchase_id references purchases.id many to one
  • wallet_ledger_entries.staff_account_id references staff_accounts.id many to one

Multiplayer Game Backend database schema in DBML

The schema as it is written: DBML, the text format DB Planner draws its diagrams from. Copy it into any DBML tool, or open it in the diagram above.

multiplayer-game-backend.dbml dbml
// Multiplayer Game Backend
// Zones (header colors): players and identity (blue), economy and store (green),
// matchmaking and matches (teal), ratings and progression (purple),
// social (coral), moderation (gray).

// ---------------------------------------------------------------------------
// PLAYERS AND IDENTITY: one game account, many platform logins
// ---------------------------------------------------------------------------

Table platforms [headercolor: #4c8bf5] {
  id uuid [pk]
  code varchar(30) [not null, unique, note: 'Your own short code per integration, e.g. pc_store_a, console_b, mobile_store_a']
  name varchar(100) [not null]
  kind platform_kind [not null]
  has_store boolean [not null, default: true, note: 'Whether purchases can arrive with a receipt from this platform']
  Note: 'Storefronts, console networks and mobile app stores the game ships on. Platforms are data, not schema, so adding one is an INSERT.'
}

Table players [headercolor: #4c8bf5] {
  id uuid [pk]
  display_name varchar(32) [not null]
  name_tag char(4) [not null, note: 'Four-digit suffix, so display names need not be unique: "Raven#4821"']
  country char(2)
  status account_status [not null, default: 'active', note: 'CACHE of active sanctions, refreshed when one starts, expires or is revoked']
  created_at timestamptz [not null, default: `now()`]
  last_login_at timestamptz
  deleted_at timestamptz [note: 'Soft delete for data-deletion requests. Ledger rows stay, keyed by an id that no longer identifies anyone']

  indexes {
    (display_name, name_tag) [unique]
  }

  Note: 'The game account, independent of any platform. Wallet, inventory and ratings hang off this id, which is what makes cross-progression possible.'
}

Table platform_identities [headercolor: #4c8bf5] {
  id uuid [pk]
  player_id uuid [not null, ref: > players.id]
  platform_id uuid [not null, ref: > platforms.id]
  external_user_id varchar(128) [not null, note: 'The account id the platform hands over after sign-in']
  external_display_name varchar(100)
  linked_at timestamptz [not null, default: `now()`]
  last_auth_at timestamptz
  unlinked_at timestamptz

  indexes {
    (platform_id, external_user_id) [note: 'Partial unique WHERE unlinked_at IS NULL: a platform account belongs to one player at a time. Moving it to another player is a deliberate merge']
    player_id
  }

  Note: 'Linked platform accounts. Sign-in looks up (platform, external id) to find the player; a player on three platforms has three rows.'
}

Table player_profiles [headercolor: #4c8bf5] {
  player_id uuid [pk, ref: - players.id]
  avatar_item_id uuid [ref: > items.id, note: 'An equipped cosmetic must be owned: checked against inventory on equip']
  banner_item_id uuid [ref: > items.id]
  title_achievement_id uuid [ref: > achievements.id, note: 'A display title unlocked by an achievement']
  account_level integer [not null, default: 1]
  account_xp bigint [not null, default: 0]
  show_online_status boolean [not null, default: true]
  updated_at timestamptz [not null, default: `now()`]
  Note: 'What other players see: equipped cosmetics, title and level. Split from players so a busy profile never locks the account row.'
}

// ---------------------------------------------------------------------------
// ECONOMY AND STORE: money is a ledger, receipts are validated once
// ---------------------------------------------------------------------------

Table currencies [headercolor: #8bc34a] {
  id uuid [pk]
  code varchar(10) [not null, unique, note: 'e.g. GOLD (soft), GEMS (premium)']
  name varchar(60) [not null]
  kind currency_kind [not null]
  max_balance bigint [note: 'Cap enforced when a credit is written; null for no cap']
  is_purchasable boolean [not null, default: false, note: 'Only premium currency is sold for real money']
  Note: 'Virtual currencies. Premium currency is bought, so it carries refund and chargeback obligations that soft currency does not.'
}

Table wallet_ledger_entries [headercolor: #8bc34a] {
  id uuid [pk]
  player_id uuid [not null, ref: > players.id]
  currency_id uuid [not null, ref: > currencies.id]
  sequence bigint [not null, note: 'Per player and currency: 1, 2, 3 with no gaps']
  amount bigint [not null, note: 'Signed: a credit is positive, a debit negative. Never zero']
  balance_after bigint [not null, note: 'Running balance, computed at insert from the previous row (locked FOR UPDATE). A CHECK keeps it at or above zero']
  reason ledger_reason [not null]
  purchase_id uuid [ref: > purchases.id]
  match_id uuid [ref: > matches.id]
  achievement_id uuid [ref: > achievements.id]
  staff_account_id uuid [ref: > staff_accounts.id, note: 'Required for admin adjustments, so an insider grant is always attributed']
  idempotency_key varchar(100) [not null, unique, note: 'e.g. purchase:<id>:credit or match:<id>:reward. A retried grant collides here instead of paying twice']
  created_at timestamptz [not null, default: `now()`]

  indexes {
    (player_id, currency_id, sequence) [unique, note: 'The current balance is the row with the highest sequence']
  }

  Note: 'The wallet. There is no balance column anywhere to UPDATE: every change to every currency is an insert here, with its cause. A duplication exploit shows up as rows with a reason, and any balance can be recomputed from history.'
}

Table items [headercolor: #8bc34a] {
  id uuid [pk]
  sku varchar(60) [not null, unique]
  name varchar(120) [not null]
  kind item_kind [not null]
  rarity item_rarity [not null]
  is_stackable boolean [not null, default: false, note: 'Consumables stack into one inventory row with a quantity']
  is_tradeable boolean [not null, default: false]
  released_at timestamptz
  retired_at timestamptz [note: 'No longer obtainable. Owned copies are kept']
  Note: 'The item catalog: everything a player can own.'
}

Table inventory_items [headercolor: #8bc34a] {
  id uuid [pk]
  player_id uuid [not null, ref: > players.id]
  item_id uuid [not null, ref: > items.id]
  quantity integer [not null, default: 1, note: 'Remaining uses for stackable consumables; 1 for everything else']
  grant_reason grant_reason [not null]
  purchase_id uuid [ref: > purchases.id]
  match_id uuid [ref: > matches.id]
  achievement_id uuid [ref: > achievements.id]
  granted_at timestamptz [not null, default: `now()`]
  expires_at timestamptz [note: 'Rentals and time-limited boosts']
  revoked_at timestamptz [note: 'Set by a refund or chargeback. The row stays as evidence']

  indexes {
    (player_id, item_id)
  }

  Note: 'Item instances a player owns, each pointing at whatever granted it. Revoking is a timestamp, so support can always answer "where did this come from?"'
}

Table store_offers [headercolor: #8bc34a] {
  id uuid [pk]
  sku varchar(60) [not null, unique]
  name varchar(120) [not null]
  price_kind offer_price_kind [not null]
  price_currency_id uuid [ref: > currencies.id, note: 'Set when priced in a virtual currency']
  price_amount bigint [note: 'In units of price_currency_id']
  platform_product_id varchar(100) [note: 'Set when priced in real money: the product id configured in each platform store. Real prices live in the store, not here']
  starts_at timestamptz
  ends_at timestamptz [note: 'Limited-time offers']
  max_per_player integer [note: 'e.g. 1 for a starter pack']
  is_active boolean [not null, default: true]
  Note: 'What the in-game store sells: a bundle of contents for one price, in real money or a virtual currency.'
}

Table offer_contents [headercolor: #8bc34a] {
  id uuid [pk]
  store_offer_id uuid [not null, ref: > store_offers.id]
  item_id uuid [ref: > items.id]
  currency_id uuid [ref: > currencies.id]
  quantity bigint [not null]
  Note: 'What an offer grants. Exactly one of item_id and currency_id per row, so a gem pack is just an offer whose only content is currency.'
}

Table purchases [headercolor: #8bc34a] {
  id uuid [pk]
  player_id uuid [not null, ref: > players.id]
  store_offer_id uuid [not null, ref: > store_offers.id]
  platform_id uuid [ref: > platforms.id, note: 'Null for purchases paid in virtual currency']
  platform_transaction_id varchar(200) [note: 'The receipt or order id issued by the platform store']
  receipt_payload text [note: 'Raw receipt as received, kept for disputes and re-validation']
  status purchase_status [not null, default: 'pending_validation']
  price_cents integer [note: 'Real-money amount as reported by the store']
  currency char(3)
  created_at timestamptz [not null, default: `now()`]
  validated_at timestamptz
  fulfilled_at timestamptz
  refunded_at timestamptz

  indexes {
    (platform_id, platform_transaction_id) [unique, note: 'Idempotent receipts: a client that resends a receipt gets the existing purchase back, never a second grant']
    (player_id, created_at)
  }

  Note: 'Every purchase, as a state machine: validate the receipt server-side with the platform, then fulfil by writing ledger and inventory rows keyed on this id. Never trust a client that says it paid.'
}

// ---------------------------------------------------------------------------
// MATCHMAKING AND MATCHES
// ---------------------------------------------------------------------------

Table seasons [headercolor: #4cd0b0] {
  id uuid [pk]
  number integer [not null, unique]
  name varchar(100) [not null]
  starts_at timestamptz [not null]
  ends_at timestamptz [not null]
  soft_reset_factor numeric(3,2) [not null, default: 0.5, note: 'How far ratings are pulled toward the mean at season start']
  Note: 'Competitive seasons. Ratings and leaderboards are scoped to one.'
}

Table game_modes [headercolor: #4cd0b0] {
  id uuid [pk]
  code varchar(30) [not null, unique, note: 'e.g. ranked_5v5, casual_ffa']
  name varchar(100) [not null]
  team_count smallint [not null]
  team_size smallint [not null]
  is_ranked boolean [not null, default: false]
  is_active boolean [not null, default: true]
  Note: 'Playlists. A rating only means something within one mode, so ratings are keyed by it.'
}

Table matchmaking_tickets [headercolor: #4cd0b0] {
  id uuid [pk]
  player_id uuid [not null, ref: > players.id, note: 'The player who queued; for a party, its leader']
  party_id uuid [ref: > parties.id]
  game_mode_id uuid [not null, ref: > game_modes.id]
  region varchar(20) [not null, note: 'e.g. eu-west, us-east']
  rating_at_queue integer [not null, note: 'Snapshot used for matching; a party queues on a combined rating']
  latency_ms jsonb [note: 'Measured ping per region, e.g. {"eu-west": 31, "us-east": 104}']
  status ticket_status [not null, default: 'queued']
  created_at timestamptz [not null, default: `now()`]
  matched_at timestamptz
  match_id uuid [ref: > matches.id]

  indexes {
    (game_mode_id, region, status, created_at) [note: 'The matchmaker scans queued tickets oldest first, widening the rating window the longer one waits']
  }

  Note: 'A request to play. Kept after matching, so time-to-match and abandoned queues can be measured.'
}

Table matches [headercolor: #4cd0b0] {
  id uuid [pk]
  game_mode_id uuid [not null, ref: > game_modes.id]
  season_id uuid [ref: > seasons.id]
  region varchar(20) [not null]
  server_id varchar(100) [note: 'Allocated dedicated server or session host']
  server_build varchar(40) [note: 'Game server version, for when a bug invalidates every match played on one build']
  status match_status [not null, default: 'allocating']
  started_at timestamptz
  ended_at timestamptz
  winning_team smallint
  Note: 'One played game, with results written by the authoritative server, never by a client. An invalidated match keeps its row but pays no rewards and moves no ratings.'
}

Table match_participants [headercolor: #4cd0b0] {
  match_id uuid [not null, ref: > matches.id]
  player_id uuid [not null, ref: > players.id]
  team smallint [not null]
  party_id uuid [ref: > parties.id]
  outcome match_outcome
  placement smallint [note: 'Finishing position, for free-for-all modes']
  score integer
  stats jsonb [note: 'Mode-specific numbers, e.g. kills, assists, objectives']
  joined_at timestamptz [not null]
  left_at timestamptz [note: 'Earlier than the match end means the player left early']

  indexes {
    (match_id, player_id) [pk]
    (player_id, joined_at) [note: 'Match history']
  }

  Note: 'Who played, on which team, and how it went for them. Rewards and rating changes are computed from these rows.'
}

// ---------------------------------------------------------------------------
// RATINGS AND PROGRESSION: history is appended, never edited
// ---------------------------------------------------------------------------

Table rating_events [headercolor: #b98cf0] {
  id uuid [pk]
  player_id uuid [not null, ref: > players.id]
  game_mode_id uuid [not null, ref: > game_modes.id]
  season_id uuid [not null, ref: > seasons.id]
  match_id uuid [ref: > matches.id, note: 'Null for season resets and decay']
  kind rating_event_kind [not null]
  rating_before integer [not null]
  rating_after integer [not null]
  uncertainty_after numeric(6,2) [note: 'Rating deviation, for systems that track confidence as well as skill']
  created_at timestamptz [not null, default: `now()`]

  indexes {
    (player_id, game_mode_id, season_id, created_at) [note: 'The rating graph on a profile']
    (player_id, match_id, kind) [unique, note: 'A match moves a player once; a later correction is a second kind of row']
  }

  Note: 'Append-only MMR history per player, per mode, per season. Undoing the games lost to a banned cheater is a new correction row, never an edit.'
}

Table player_ratings [headercolor: #b98cf0] {
  player_id uuid [not null, ref: > players.id]
  game_mode_id uuid [not null, ref: > game_modes.id]
  season_id uuid [not null, ref: > seasons.id]
  rating integer [not null]
  uncertainty numeric(6,2)
  games_played integer [not null, default: 0]
  wins integer [not null, default: 0]
  last_rating_event_id uuid [not null, ref: > rating_events.id, note: 'The event this cache was built from']
  updated_at timestamptz [not null]

  indexes {
    (player_id, game_mode_id, season_id) [pk]
    (game_mode_id, season_id, rating) [note: 'Live rank lookups between snapshots']
  }

  Note: 'CACHE of the latest rating_events row, for the matchmaker and the profile. Rebuildable from history at any time.'
}

Table leaderboard_snapshots [headercolor: #b98cf0] {
  id uuid [pk]
  game_mode_id uuid [not null, ref: > game_modes.id]
  season_id uuid [not null, ref: > seasons.id]
  region varchar(20) [note: 'Null for the global board']
  taken_at timestamptz [not null]
  is_final boolean [not null, default: false, note: 'The end-of-season board that season rewards are paid from']
  Note: 'A leaderboard frozen at a moment, e.g. every 15 minutes. Readers page through a snapshot instead of sorting a live table, and the final one is the permanent record.'
}

Table leaderboard_entries [headercolor: #b98cf0] {
  snapshot_id uuid [not null, ref: > leaderboard_snapshots.id]
  rank integer [not null, note: 'Ties broken by who reached the rating first']
  player_id uuid [not null, ref: > players.id]
  rating integer [not null]
  display_name varchar(40) [not null, note: 'Copied at snapshot time, so the board reads without a join and shows the name used then']

  indexes {
    (snapshot_id, rank) [pk]
    (snapshot_id, player_id) [unique, note: 'Find my rank']
  }

  Note: 'The ranked rows of a snapshot. Usually only the top few thousand are stored.'
}

Table achievements [headercolor: #b98cf0] {
  id uuid [pk]
  code varchar(60) [not null, unique]
  name varchar(120) [not null]
  description varchar(500) [not null]
  target_value integer [not null, default: 1, note: 'e.g. 100 for "win 100 ranked matches"']
  is_hidden boolean [not null, default: false, note: 'Secret until unlocked']
  reward_item_id uuid [ref: > items.id]
  reward_currency_id uuid [ref: > currencies.id]
  reward_amount bigint
  Note: 'Achievement definitions and what they pay out.'
}

Table player_achievements [headercolor: #b98cf0] {
  player_id uuid [not null, ref: > players.id]
  achievement_id uuid [not null, ref: > achievements.id]
  progress integer [not null, default: 0]
  completed_at timestamptz
  reward_claimed_at timestamptz [note: 'Claiming writes the ledger or inventory row; its idempotency key stops a double claim']
  updated_at timestamptz [not null]

  indexes {
    (player_id, achievement_id) [pk]
  }

  Note: 'Progress toward each achievement, created on first progress.'
}

// ---------------------------------------------------------------------------
// SOCIAL: friends, parties, guilds
// ---------------------------------------------------------------------------

Table friendships [headercolor: #f07178] {
  player_low_id uuid [not null, ref: > players.id, note: 'The smaller of the two ids (CHECK player_low_id < player_high_id)']
  player_high_id uuid [not null, ref: > players.id]
  requested_by uuid [not null, ref: > players.id]
  status friendship_status [not null, default: 'pending']
  created_at timestamptz [not null, default: `now()`]
  accepted_at timestamptz

  indexes {
    (player_low_id, player_high_id) [pk]
    player_high_id
  }

  Note: 'Mutual friendships stored once, as an ordered pair, so A-B and B-A can never both exist. A friends list reads both columns.'
}

Table parties [headercolor: #f07178] {
  id uuid [pk]
  leader_id uuid [not null, ref: > players.id]
  game_mode_id uuid [ref: > game_modes.id, note: 'What the party is about to queue for']
  max_size smallint [not null]
  invite_code varchar(12) [unique]
  created_at timestamptz [not null, default: `now()`]
  disbanded_at timestamptz
  Note: 'A group that queues together. Short-lived, but kept for match history and for spotting win-trading groups.'
}

Table party_members [headercolor: #f07178] {
  party_id uuid [not null, ref: > parties.id]
  player_id uuid [not null, ref: > players.id]
  joined_at timestamptz [not null, default: `now()`]
  left_at timestamptz

  indexes {
    (party_id, player_id) [pk]
    player_id [note: 'Partial unique WHERE left_at IS NULL: one party at a time']
  }

  Note: 'Who is, or was, in a party.'
}

Table guilds [headercolor: #f07178] {
  id uuid [pk]
  name varchar(50) [not null, unique]
  tag varchar(5) [not null, unique, note: 'Short tag shown beside member names, e.g. [ABC]']
  description varchar(500)
  member_limit smallint [not null, default: 50]
  is_open boolean [not null, default: false, note: 'Open guilds accept joins without an invite']
  created_at timestamptz [not null, default: `now()`]
  disbanded_at timestamptz
  Note: 'Long-lived player organizations: guilds, clans, crews.'
}

Table guild_members [headercolor: #f07178] {
  id uuid [pk]
  guild_id uuid [not null, ref: > guilds.id]
  player_id uuid [not null, ref: > players.id]
  role guild_role [not null, default: 'member']
  joined_at timestamptz [not null, default: `now()`]
  left_at timestamptz
  left_reason guild_leave_reason

  indexes {
    player_id [note: 'Partial unique WHERE left_at IS NULL: one guild at a time']
    (guild_id, role) [note: 'Partial unique WHERE role = leader AND left_at IS NULL: exactly one leader']
  }

  Note: 'Membership history with roles. Leadership is a role, not a column on guilds, so a handover is two updates in one transaction.'
}

// ---------------------------------------------------------------------------
// MODERATION
// ---------------------------------------------------------------------------

Table staff_accounts [headercolor: #90a4ae] {
  id uuid [pk]
  email varchar(254) [not null, unique]
  name varchar(120) [not null]
  role staff_role [not null]
  disabled_at timestamptz
  Note: 'Support agents, moderators and live-ops staff. Kept apart from players: staff never act through a game account.'
}

Table player_reports [headercolor: #90a4ae] {
  id uuid [pk]
  reporter_id uuid [not null, ref: > players.id]
  reported_player_id uuid [not null, ref: > players.id]
  match_id uuid [ref: > matches.id, note: 'The match it happened in, so a reviewer can pull the replay']
  reason report_reason [not null]
  details varchar(1000)
  created_at timestamptz [not null, default: `now()`]
  reviewed_at timestamptz
  reviewed_by uuid [ref: > staff_accounts.id]
  sanction_id uuid [ref: > sanctions.id, note: 'The sanction it led to, if any']

  indexes {
    (reported_player_id, created_at)
  }

  Note: 'In-game reports. Volume per reported player feeds automated review; one report rarely decides anything alone.'
}

Table sanctions [headercolor: #90a4ae] {
  id uuid [pk]
  player_id uuid [not null, ref: > players.id]
  kind sanction_kind [not null]
  reason report_reason [not null]
  details text
  issued_by uuid [ref: > staff_accounts.id, note: 'Null for automated systems such as anti-cheat']
  evidence_match_id uuid [ref: > matches.id]
  starts_at timestamptz [not null, default: `now()`]
  expires_at timestamptz [note: 'Null for permanent']
  revoked_at timestamptz [note: 'Overturned on appeal. The row stays']
  revoked_by uuid [ref: > staff_accounts.id]
  created_at timestamptz [not null, default: `now()`]

  indexes {
    (player_id, expires_at) [note: 'Active: starts_at <= now() AND (expires_at IS NULL OR expires_at > now()) AND revoked_at IS NULL']
  }

  Note: 'Warnings, chat mutes, queue cooldowns, ranked bans and account bans, each a row with a time window. A ban is a sanction, so its history and appeal live in one place; players.status only caches what is active.'
}

// ---------------------------------------------------------------------------
// ENUMS
// ---------------------------------------------------------------------------

Enum platform_kind {
  pc
  console
  mobile
  web
}

Enum account_status {
  active
  suspended
  banned
  deleted
}

Enum currency_kind {
  soft [note: 'Earned by playing']
  premium [note: 'Bought with real money']
  event [note: 'Time-limited, expires with its event']
}

Enum ledger_reason {
  purchase_credit
  store_spend
  match_reward
  achievement_reward
  season_reward
  refund_reversal
  chargeback_reversal
  admin_adjustment
  expiry
}

Enum item_kind {
  character
  skin
  weapon
  emote
  avatar
  banner
  consumable
  boost
}

Enum item_rarity {
  common
  uncommon
  rare
  epic
  legendary
}

Enum grant_reason {
  purchase
  match_reward
  achievement
  season_reward
  starter
  admin_grant
}

Enum offer_price_kind {
  real_money
  virtual_currency
}

Enum purchase_status {
  pending_validation
  validated
  fulfilled
  rejected
  refunded
  chargeback
}

Enum ticket_status {
  queued
  matched
  cancelled
  timed_out
}

Enum match_status {
  allocating
  in_progress
  completed
  abandoned
  invalidated
}

Enum match_outcome {
  win
  loss
  draw
  abandoned
}

Enum rating_event_kind {
  match
  season_reset
  decay
  correction
}

Enum friendship_status {
  pending
  accepted
}

Enum guild_role {
  leader
  officer
  member
  recruit
}

Enum guild_leave_reason {
  left
  kicked
  guild_disbanded
}

Enum staff_role {
  support
  moderator
  live_ops
  admin
}

Enum report_reason {
  cheating
  griefing
  abusive_chat
  offensive_name
  win_trading
  account_sharing
  other
}

Enum sanction_kind {
  warning
  chat_mute
  matchmaking_cooldown
  ranked_ban
  temporary_ban
  permanent_ban
}

Multiplayer Game Backend database schema as SQL

The same schema as CREATE TABLE statements, exported by DB Planner. PostgreSQL is shown first; MySQL and SQL Server are below it.

PostgreSQL
postgresql.sql PostgreSQL
CREATE TYPE "platform_kind" AS ENUM (
  'pc',
  'console',
  'mobile',
  'web'
);

CREATE TYPE "account_status" AS ENUM (
  'active',
  'suspended',
  'banned',
  'deleted'
);

CREATE TYPE "currency_kind" AS ENUM (
  'soft',
  'premium',
  'event'
);

CREATE TYPE "ledger_reason" AS ENUM (
  'purchase_credit',
  'store_spend',
  'match_reward',
  'achievement_reward',
  'season_reward',
  'refund_reversal',
  'chargeback_reversal',
  'admin_adjustment',
  'expiry'
);

CREATE TYPE "item_kind" AS ENUM (
  'character',
  'skin',
  'weapon',
  'emote',
  'avatar',
  'banner',
  'consumable',
  'boost'
);

CREATE TYPE "item_rarity" AS ENUM (
  'common',
  'uncommon',
  'rare',
  'epic',
  'legendary'
);

CREATE TYPE "grant_reason" AS ENUM (
  'purchase',
  'match_reward',
  'achievement',
  'season_reward',
  'starter',
  'admin_grant'
);

CREATE TYPE "offer_price_kind" AS ENUM (
  'real_money',
  'virtual_currency'
);

CREATE TYPE "purchase_status" AS ENUM (
  'pending_validation',
  'validated',
  'fulfilled',
  'rejected',
  'refunded',
  'chargeback'
);

CREATE TYPE "ticket_status" AS ENUM (
  'queued',
  'matched',
  'cancelled',
  'timed_out'
);

CREATE TYPE "match_status" AS ENUM (
  'allocating',
  'in_progress',
  'completed',
  'abandoned',
  'invalidated'
);

CREATE TYPE "match_outcome" AS ENUM (
  'win',
  'loss',
  'draw',
  'abandoned'
);

CREATE TYPE "rating_event_kind" AS ENUM (
  'match',
  'season_reset',
  'decay',
  'correction'
);

CREATE TYPE "friendship_status" AS ENUM (
  'pending',
  'accepted'
);

CREATE TYPE "guild_role" AS ENUM (
  'leader',
  'officer',
  'member',
  'recruit'
);

CREATE TYPE "guild_leave_reason" AS ENUM (
  'left',
  'kicked',
  'guild_disbanded'
);

CREATE TYPE "staff_role" AS ENUM (
  'support',
  'moderator',
  'live_ops',
  'admin'
);

CREATE TYPE "report_reason" AS ENUM (
  'cheating',
  'griefing',
  'abusive_chat',
  'offensive_name',
  'win_trading',
  'account_sharing',
  'other'
);

CREATE TYPE "sanction_kind" AS ENUM (
  'warning',
  'chat_mute',
  'matchmaking_cooldown',
  'ranked_ban',
  'temporary_ban',
  'permanent_ban'
);

CREATE TABLE "platforms" (
  "id" uuid PRIMARY KEY,
  "code" varchar(30) UNIQUE NOT NULL,
  "name" varchar(100) NOT NULL,
  "kind" platform_kind NOT NULL,
  "has_store" boolean NOT NULL DEFAULT true
);

CREATE TABLE "players" (
  "id" uuid PRIMARY KEY,
  "display_name" varchar(32) NOT NULL,
  "name_tag" char(4) NOT NULL,
  "country" char(2),
  "status" account_status NOT NULL DEFAULT 'active',
  "created_at" timestamptz NOT NULL DEFAULT (now()),
  "last_login_at" timestamptz,
  "deleted_at" timestamptz
);

CREATE TABLE "platform_identities" (
  "id" uuid PRIMARY KEY,
  "player_id" uuid NOT NULL,
  "platform_id" uuid NOT NULL,
  "external_user_id" varchar(128) NOT NULL,
  "external_display_name" varchar(100),
  "linked_at" timestamptz NOT NULL DEFAULT (now()),
  "last_auth_at" timestamptz,
  "unlinked_at" timestamptz
);

CREATE TABLE "player_profiles" (
  "player_id" uuid PRIMARY KEY,
  "avatar_item_id" uuid,
  "banner_item_id" uuid,
  "title_achievement_id" uuid,
  "account_level" integer NOT NULL DEFAULT 1,
  "account_xp" bigint NOT NULL DEFAULT 0,
  "show_online_status" boolean NOT NULL DEFAULT true,
  "updated_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "currencies" (
  "id" uuid PRIMARY KEY,
  "code" varchar(10) UNIQUE NOT NULL,
  "name" varchar(60) NOT NULL,
  "kind" currency_kind NOT NULL,
  "max_balance" bigint,
  "is_purchasable" boolean NOT NULL DEFAULT false
);

CREATE TABLE "wallet_ledger_entries" (
  "id" uuid PRIMARY KEY,
  "player_id" uuid NOT NULL,
  "currency_id" uuid NOT NULL,
  "sequence" bigint NOT NULL,
  "amount" bigint NOT NULL,
  "balance_after" bigint NOT NULL,
  "reason" ledger_reason NOT NULL,
  "purchase_id" uuid,
  "match_id" uuid,
  "achievement_id" uuid,
  "staff_account_id" uuid,
  "idempotency_key" varchar(100) UNIQUE NOT NULL,
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "items" (
  "id" uuid PRIMARY KEY,
  "sku" varchar(60) UNIQUE NOT NULL,
  "name" varchar(120) NOT NULL,
  "kind" item_kind NOT NULL,
  "rarity" item_rarity NOT NULL,
  "is_stackable" boolean NOT NULL DEFAULT false,
  "is_tradeable" boolean NOT NULL DEFAULT false,
  "released_at" timestamptz,
  "retired_at" timestamptz
);

CREATE TABLE "inventory_items" (
  "id" uuid PRIMARY KEY,
  "player_id" uuid NOT NULL,
  "item_id" uuid NOT NULL,
  "quantity" integer NOT NULL DEFAULT 1,
  "grant_reason" grant_reason NOT NULL,
  "purchase_id" uuid,
  "match_id" uuid,
  "achievement_id" uuid,
  "granted_at" timestamptz NOT NULL DEFAULT (now()),
  "expires_at" timestamptz,
  "revoked_at" timestamptz
);

CREATE TABLE "store_offers" (
  "id" uuid PRIMARY KEY,
  "sku" varchar(60) UNIQUE NOT NULL,
  "name" varchar(120) NOT NULL,
  "price_kind" offer_price_kind NOT NULL,
  "price_currency_id" uuid,
  "price_amount" bigint,
  "platform_product_id" varchar(100),
  "starts_at" timestamptz,
  "ends_at" timestamptz,
  "max_per_player" integer,
  "is_active" boolean NOT NULL DEFAULT true
);

CREATE TABLE "offer_contents" (
  "id" uuid PRIMARY KEY,
  "store_offer_id" uuid NOT NULL,
  "item_id" uuid,
  "currency_id" uuid,
  "quantity" bigint NOT NULL
);

CREATE TABLE "purchases" (
  "id" uuid PRIMARY KEY,
  "player_id" uuid NOT NULL,
  "store_offer_id" uuid NOT NULL,
  "platform_id" uuid,
  "platform_transaction_id" varchar(200),
  "receipt_payload" text,
  "status" purchase_status NOT NULL DEFAULT 'pending_validation',
  "price_cents" integer,
  "currency" char(3),
  "created_at" timestamptz NOT NULL DEFAULT (now()),
  "validated_at" timestamptz,
  "fulfilled_at" timestamptz,
  "refunded_at" timestamptz
);

CREATE TABLE "seasons" (
  "id" uuid PRIMARY KEY,
  "number" integer UNIQUE NOT NULL,
  "name" varchar(100) NOT NULL,
  "starts_at" timestamptz NOT NULL,
  "ends_at" timestamptz NOT NULL,
  "soft_reset_factor" numeric(3,2) NOT NULL DEFAULT 0.5
);

CREATE TABLE "game_modes" (
  "id" uuid PRIMARY KEY,
  "code" varchar(30) UNIQUE NOT NULL,
  "name" varchar(100) NOT NULL,
  "team_count" smallint NOT NULL,
  "team_size" smallint NOT NULL,
  "is_ranked" boolean NOT NULL DEFAULT false,
  "is_active" boolean NOT NULL DEFAULT true
);

CREATE TABLE "matchmaking_tickets" (
  "id" uuid PRIMARY KEY,
  "player_id" uuid NOT NULL,
  "party_id" uuid,
  "game_mode_id" uuid NOT NULL,
  "region" varchar(20) NOT NULL,
  "rating_at_queue" integer NOT NULL,
  "latency_ms" jsonb,
  "status" ticket_status NOT NULL DEFAULT 'queued',
  "created_at" timestamptz NOT NULL DEFAULT (now()),
  "matched_at" timestamptz,
  "match_id" uuid
);

CREATE TABLE "matches" (
  "id" uuid PRIMARY KEY,
  "game_mode_id" uuid NOT NULL,
  "season_id" uuid,
  "region" varchar(20) NOT NULL,
  "server_id" varchar(100),
  "server_build" varchar(40),
  "status" match_status NOT NULL DEFAULT 'allocating',
  "started_at" timestamptz,
  "ended_at" timestamptz,
  "winning_team" smallint
);

CREATE TABLE "match_participants" (
  "match_id" uuid NOT NULL,
  "player_id" uuid NOT NULL,
  "team" smallint NOT NULL,
  "party_id" uuid,
  "outcome" match_outcome,
  "placement" smallint,
  "score" integer,
  "stats" jsonb,
  "joined_at" timestamptz NOT NULL,
  "left_at" timestamptz,
  PRIMARY KEY ("match_id", "player_id")
);

CREATE TABLE "rating_events" (
  "id" uuid PRIMARY KEY,
  "player_id" uuid NOT NULL,
  "game_mode_id" uuid NOT NULL,
  "season_id" uuid NOT NULL,
  "match_id" uuid,
  "kind" rating_event_kind NOT NULL,
  "rating_before" integer NOT NULL,
  "rating_after" integer NOT NULL,
  "uncertainty_after" numeric(6,2),
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "player_ratings" (
  "player_id" uuid NOT NULL,
  "game_mode_id" uuid NOT NULL,
  "season_id" uuid NOT NULL,
  "rating" integer NOT NULL,
  "uncertainty" numeric(6,2),
  "games_played" integer NOT NULL DEFAULT 0,
  "wins" integer NOT NULL DEFAULT 0,
  "last_rating_event_id" uuid NOT NULL,
  "updated_at" timestamptz NOT NULL,
  PRIMARY KEY ("player_id", "game_mode_id", "season_id")
);

CREATE TABLE "leaderboard_snapshots" (
  "id" uuid PRIMARY KEY,
  "game_mode_id" uuid NOT NULL,
  "season_id" uuid NOT NULL,
  "region" varchar(20),
  "taken_at" timestamptz NOT NULL,
  "is_final" boolean NOT NULL DEFAULT false
);

CREATE TABLE "leaderboard_entries" (
  "snapshot_id" uuid NOT NULL,
  "rank" integer NOT NULL,
  "player_id" uuid NOT NULL,
  "rating" integer NOT NULL,
  "display_name" varchar(40) NOT NULL,
  PRIMARY KEY ("snapshot_id", "rank")
);

CREATE TABLE "achievements" (
  "id" uuid PRIMARY KEY,
  "code" varchar(60) UNIQUE NOT NULL,
  "name" varchar(120) NOT NULL,
  "description" varchar(500) NOT NULL,
  "target_value" integer NOT NULL DEFAULT 1,
  "is_hidden" boolean NOT NULL DEFAULT false,
  "reward_item_id" uuid,
  "reward_currency_id" uuid,
  "reward_amount" bigint
);

CREATE TABLE "player_achievements" (
  "player_id" uuid NOT NULL,
  "achievement_id" uuid NOT NULL,
  "progress" integer NOT NULL DEFAULT 0,
  "completed_at" timestamptz,
  "reward_claimed_at" timestamptz,
  "updated_at" timestamptz NOT NULL,
  PRIMARY KEY ("player_id", "achievement_id")
);

CREATE TABLE "friendships" (
  "player_low_id" uuid NOT NULL,
  "player_high_id" uuid NOT NULL,
  "requested_by" uuid NOT NULL,
  "status" friendship_status NOT NULL DEFAULT 'pending',
  "created_at" timestamptz NOT NULL DEFAULT (now()),
  "accepted_at" timestamptz,
  PRIMARY KEY ("player_low_id", "player_high_id")
);

CREATE TABLE "parties" (
  "id" uuid PRIMARY KEY,
  "leader_id" uuid NOT NULL,
  "game_mode_id" uuid,
  "max_size" smallint NOT NULL,
  "invite_code" varchar(12) UNIQUE,
  "created_at" timestamptz NOT NULL DEFAULT (now()),
  "disbanded_at" timestamptz
);

CREATE TABLE "party_members" (
  "party_id" uuid NOT NULL,
  "player_id" uuid NOT NULL,
  "joined_at" timestamptz NOT NULL DEFAULT (now()),
  "left_at" timestamptz,
  PRIMARY KEY ("party_id", "player_id")
);

CREATE TABLE "guilds" (
  "id" uuid PRIMARY KEY,
  "name" varchar(50) UNIQUE NOT NULL,
  "tag" varchar(5) UNIQUE NOT NULL,
  "description" varchar(500),
  "member_limit" smallint NOT NULL DEFAULT 50,
  "is_open" boolean NOT NULL DEFAULT false,
  "created_at" timestamptz NOT NULL DEFAULT (now()),
  "disbanded_at" timestamptz
);

CREATE TABLE "guild_members" (
  "id" uuid PRIMARY KEY,
  "guild_id" uuid NOT NULL,
  "player_id" uuid NOT NULL,
  "role" guild_role NOT NULL DEFAULT 'member',
  "joined_at" timestamptz NOT NULL DEFAULT (now()),
  "left_at" timestamptz,
  "left_reason" guild_leave_reason
);

CREATE TABLE "staff_accounts" (
  "id" uuid PRIMARY KEY,
  "email" varchar(254) UNIQUE NOT NULL,
  "name" varchar(120) NOT NULL,
  "role" staff_role NOT NULL,
  "disabled_at" timestamptz
);

CREATE TABLE "player_reports" (
  "id" uuid PRIMARY KEY,
  "reporter_id" uuid NOT NULL,
  "reported_player_id" uuid NOT NULL,
  "match_id" uuid,
  "reason" report_reason NOT NULL,
  "details" varchar(1000),
  "created_at" timestamptz NOT NULL DEFAULT (now()),
  "reviewed_at" timestamptz,
  "reviewed_by" uuid,
  "sanction_id" uuid
);

CREATE TABLE "sanctions" (
  "id" uuid PRIMARY KEY,
  "player_id" uuid NOT NULL,
  "kind" sanction_kind NOT NULL,
  "reason" report_reason NOT NULL,
  "details" text,
  "issued_by" uuid,
  "evidence_match_id" uuid,
  "starts_at" timestamptz NOT NULL DEFAULT (now()),
  "expires_at" timestamptz,
  "revoked_at" timestamptz,
  "revoked_by" uuid,
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE UNIQUE INDEX ON "players" ("display_name", "name_tag");

CREATE INDEX ON "platform_identities" ("platform_id", "external_user_id");

CREATE INDEX ON "platform_identities" ("player_id");

CREATE UNIQUE INDEX ON "wallet_ledger_entries" ("player_id", "currency_id", "sequence");

CREATE INDEX ON "inventory_items" ("player_id", "item_id");

CREATE UNIQUE INDEX ON "purchases" ("platform_id", "platform_transaction_id");

CREATE INDEX ON "purchases" ("player_id", "created_at");

CREATE INDEX ON "matchmaking_tickets" ("game_mode_id", "region", "status", "created_at");

CREATE INDEX ON "match_participants" ("player_id", "joined_at");

CREATE INDEX ON "rating_events" ("player_id", "game_mode_id", "season_id", "created_at");

CREATE UNIQUE INDEX ON "rating_events" ("player_id", "match_id", "kind");

CREATE INDEX ON "player_ratings" ("game_mode_id", "season_id", "rating");

CREATE UNIQUE INDEX ON "leaderboard_entries" ("snapshot_id", "player_id");

CREATE INDEX ON "friendships" ("player_high_id");

CREATE INDEX ON "party_members" ("player_id");

CREATE INDEX ON "guild_members" ("player_id");

CREATE INDEX ON "guild_members" ("guild_id", "role");

CREATE INDEX ON "player_reports" ("reported_player_id", "created_at");

CREATE INDEX ON "sanctions" ("player_id", "expires_at");

COMMENT ON TABLE "platforms" IS 'Storefronts, console networks and mobile app stores the game ships on. Platforms are data, not schema, so adding one is an INSERT.';

COMMENT ON COLUMN "platforms"."code" IS 'Your own short code per integration, e.g. pc_store_a, console_b, mobile_store_a';

COMMENT ON COLUMN "platforms"."has_store" IS 'Whether purchases can arrive with a receipt from this platform';

COMMENT ON TABLE "players" IS 'The game account, independent of any platform. Wallet, inventory and ratings hang off this id, which is what makes cross-progression possible.';

COMMENT ON COLUMN "players"."name_tag" IS 'Four-digit suffix, so display names need not be unique: "Raven#4821"';

COMMENT ON COLUMN "players"."status" IS 'CACHE of active sanctions, refreshed when one starts, expires or is revoked';

COMMENT ON COLUMN "players"."deleted_at" IS 'Soft delete for data-deletion requests. Ledger rows stay, keyed by an id that no longer identifies anyone';

COMMENT ON TABLE "platform_identities" IS 'Linked platform accounts. Sign-in looks up (platform, external id) to find the player; a player on three platforms has three rows.';

COMMENT ON COLUMN "platform_identities"."external_user_id" IS 'The account id the platform hands over after sign-in';

COMMENT ON TABLE "player_profiles" IS 'What other players see: equipped cosmetics, title and level. Split from players so a busy profile never locks the account row.';

COMMENT ON COLUMN "player_profiles"."avatar_item_id" IS 'An equipped cosmetic must be owned: checked against inventory on equip';

COMMENT ON COLUMN "player_profiles"."title_achievement_id" IS 'A display title unlocked by an achievement';

COMMENT ON TABLE "currencies" IS 'Virtual currencies. Premium currency is bought, so it carries refund and chargeback obligations that soft currency does not.';

COMMENT ON COLUMN "currencies"."code" IS 'e.g. GOLD (soft), GEMS (premium)';

COMMENT ON COLUMN "currencies"."max_balance" IS 'Cap enforced when a credit is written; null for no cap';

COMMENT ON COLUMN "currencies"."is_purchasable" IS 'Only premium currency is sold for real money';

COMMENT ON TABLE "wallet_ledger_entries" IS 'The wallet. There is no balance column anywhere to UPDATE: every change to every currency is an insert here, with its cause. A duplication exploit shows up as rows with a reason, and any balance can be recomputed from history.';

COMMENT ON COLUMN "wallet_ledger_entries"."sequence" IS 'Per player and currency: 1, 2, 3 with no gaps';

COMMENT ON COLUMN "wallet_ledger_entries"."amount" IS 'Signed: a credit is positive, a debit negative. Never zero';

COMMENT ON COLUMN "wallet_ledger_entries"."balance_after" IS 'Running balance, computed at insert from the previous row (locked FOR UPDATE). A CHECK keeps it at or above zero';

COMMENT ON COLUMN "wallet_ledger_entries"."staff_account_id" IS 'Required for admin adjustments, so an insider grant is always attributed';

COMMENT ON COLUMN "wallet_ledger_entries"."idempotency_key" IS 'e.g. purchase:<id>:credit or match:<id>:reward. A retried grant collides here instead of paying twice';

COMMENT ON TABLE "items" IS 'The item catalog: everything a player can own.';

COMMENT ON COLUMN "items"."is_stackable" IS 'Consumables stack into one inventory row with a quantity';

COMMENT ON COLUMN "items"."retired_at" IS 'No longer obtainable. Owned copies are kept';

COMMENT ON TABLE "inventory_items" IS 'Item instances a player owns, each pointing at whatever granted it. Revoking is a timestamp, so support can always answer "where did this come from?"';

COMMENT ON COLUMN "inventory_items"."quantity" IS 'Remaining uses for stackable consumables; 1 for everything else';

COMMENT ON COLUMN "inventory_items"."expires_at" IS 'Rentals and time-limited boosts';

COMMENT ON COLUMN "inventory_items"."revoked_at" IS 'Set by a refund or chargeback. The row stays as evidence';

COMMENT ON TABLE "store_offers" IS 'What the in-game store sells: a bundle of contents for one price, in real money or a virtual currency.';

COMMENT ON COLUMN "store_offers"."price_currency_id" IS 'Set when priced in a virtual currency';

COMMENT ON COLUMN "store_offers"."price_amount" IS 'In units of price_currency_id';

COMMENT ON COLUMN "store_offers"."platform_product_id" IS 'Set when priced in real money: the product id configured in each platform store. Real prices live in the store, not here';

COMMENT ON COLUMN "store_offers"."ends_at" IS 'Limited-time offers';

COMMENT ON COLUMN "store_offers"."max_per_player" IS 'e.g. 1 for a starter pack';

COMMENT ON TABLE "offer_contents" IS 'What an offer grants. Exactly one of item_id and currency_id per row, so a gem pack is just an offer whose only content is currency.';

COMMENT ON TABLE "purchases" IS 'Every purchase, as a state machine: validate the receipt server-side with the platform, then fulfil by writing ledger and inventory rows keyed on this id. Never trust a client that says it paid.';

COMMENT ON COLUMN "purchases"."platform_id" IS 'Null for purchases paid in virtual currency';

COMMENT ON COLUMN "purchases"."platform_transaction_id" IS 'The receipt or order id issued by the platform store';

COMMENT ON COLUMN "purchases"."receipt_payload" IS 'Raw receipt as received, kept for disputes and re-validation';

COMMENT ON COLUMN "purchases"."price_cents" IS 'Real-money amount as reported by the store';

COMMENT ON TABLE "seasons" IS 'Competitive seasons. Ratings and leaderboards are scoped to one.';

COMMENT ON COLUMN "seasons"."soft_reset_factor" IS 'How far ratings are pulled toward the mean at season start';

COMMENT ON TABLE "game_modes" IS 'Playlists. A rating only means something within one mode, so ratings are keyed by it.';

COMMENT ON COLUMN "game_modes"."code" IS 'e.g. ranked_5v5, casual_ffa';

COMMENT ON TABLE "matchmaking_tickets" IS 'A request to play. Kept after matching, so time-to-match and abandoned queues can be measured.';

COMMENT ON COLUMN "matchmaking_tickets"."player_id" IS 'The player who queued; for a party, its leader';

COMMENT ON COLUMN "matchmaking_tickets"."region" IS 'e.g. eu-west, us-east';

COMMENT ON COLUMN "matchmaking_tickets"."rating_at_queue" IS 'Snapshot used for matching; a party queues on a combined rating';

COMMENT ON COLUMN "matchmaking_tickets"."latency_ms" IS 'Measured ping per region, e.g. {"eu-west": 31, "us-east": 104}';

COMMENT ON TABLE "matches" IS 'One played game, with results written by the authoritative server, never by a client. An invalidated match keeps its row but pays no rewards and moves no ratings.';

COMMENT ON COLUMN "matches"."server_id" IS 'Allocated dedicated server or session host';

COMMENT ON COLUMN "matches"."server_build" IS 'Game server version, for when a bug invalidates every match played on one build';

COMMENT ON TABLE "match_participants" IS 'Who played, on which team, and how it went for them. Rewards and rating changes are computed from these rows.';

COMMENT ON COLUMN "match_participants"."placement" IS 'Finishing position, for free-for-all modes';

COMMENT ON COLUMN "match_participants"."stats" IS 'Mode-specific numbers, e.g. kills, assists, objectives';

COMMENT ON COLUMN "match_participants"."left_at" IS 'Earlier than the match end means the player left early';

COMMENT ON TABLE "rating_events" IS 'Append-only MMR history per player, per mode, per season. Undoing the games lost to a banned cheater is a new correction row, never an edit.';

COMMENT ON COLUMN "rating_events"."match_id" IS 'Null for season resets and decay';

COMMENT ON COLUMN "rating_events"."uncertainty_after" IS 'Rating deviation, for systems that track confidence as well as skill';

COMMENT ON TABLE "player_ratings" IS 'CACHE of the latest rating_events row, for the matchmaker and the profile. Rebuildable from history at any time.';

COMMENT ON COLUMN "player_ratings"."last_rating_event_id" IS 'The event this cache was built from';

COMMENT ON TABLE "leaderboard_snapshots" IS 'A leaderboard frozen at a moment, e.g. every 15 minutes. Readers page through a snapshot instead of sorting a live table, and the final one is the permanent record.';

COMMENT ON COLUMN "leaderboard_snapshots"."region" IS 'Null for the global board';

COMMENT ON COLUMN "leaderboard_snapshots"."is_final" IS 'The end-of-season board that season rewards are paid from';

COMMENT ON TABLE "leaderboard_entries" IS 'The ranked rows of a snapshot. Usually only the top few thousand are stored.';

COMMENT ON COLUMN "leaderboard_entries"."rank" IS 'Ties broken by who reached the rating first';

COMMENT ON COLUMN "leaderboard_entries"."display_name" IS 'Copied at snapshot time, so the board reads without a join and shows the name used then';

COMMENT ON TABLE "achievements" IS 'Achievement definitions and what they pay out.';

COMMENT ON COLUMN "achievements"."target_value" IS 'e.g. 100 for "win 100 ranked matches"';

COMMENT ON COLUMN "achievements"."is_hidden" IS 'Secret until unlocked';

COMMENT ON TABLE "player_achievements" IS 'Progress toward each achievement, created on first progress.';

COMMENT ON COLUMN "player_achievements"."reward_claimed_at" IS 'Claiming writes the ledger or inventory row; its idempotency key stops a double claim';

COMMENT ON TABLE "friendships" IS 'Mutual friendships stored once, as an ordered pair, so A-B and B-A can never both exist. A friends list reads both columns.';

COMMENT ON COLUMN "friendships"."player_low_id" IS 'The smaller of the two ids (CHECK player_low_id < player_high_id)';

COMMENT ON TABLE "parties" IS 'A group that queues together. Short-lived, but kept for match history and for spotting win-trading groups.';

COMMENT ON COLUMN "parties"."game_mode_id" IS 'What the party is about to queue for';

COMMENT ON TABLE "party_members" IS 'Who is, or was, in a party.';

COMMENT ON TABLE "guilds" IS 'Long-lived player organizations: guilds, clans, crews.';

COMMENT ON COLUMN "guilds"."tag" IS 'Short tag shown beside member names, e.g. [ABC]';

COMMENT ON COLUMN "guilds"."is_open" IS 'Open guilds accept joins without an invite';

COMMENT ON TABLE "guild_members" IS 'Membership history with roles. Leadership is a role, not a column on guilds, so a handover is two updates in one transaction.';

COMMENT ON TABLE "staff_accounts" IS 'Support agents, moderators and live-ops staff. Kept apart from players: staff never act through a game account.';

COMMENT ON TABLE "player_reports" IS 'In-game reports. Volume per reported player feeds automated review; one report rarely decides anything alone.';

COMMENT ON COLUMN "player_reports"."match_id" IS 'The match it happened in, so a reviewer can pull the replay';

COMMENT ON COLUMN "player_reports"."sanction_id" IS 'The sanction it led to, if any';

COMMENT ON TABLE "sanctions" IS 'Warnings, chat mutes, queue cooldowns, ranked bans and account bans, each a row with a time window. A ban is a sanction, so its history and appeal live in one place; players.status only caches what is active.';

COMMENT ON COLUMN "sanctions"."issued_by" IS 'Null for automated systems such as anti-cheat';

COMMENT ON COLUMN "sanctions"."expires_at" IS 'Null for permanent';

COMMENT ON COLUMN "sanctions"."revoked_at" IS 'Overturned on appeal. The row stays';

ALTER TABLE "platform_identities" ADD FOREIGN KEY ("player_id") REFERENCES "players" ("id");

ALTER TABLE "platform_identities" ADD FOREIGN KEY ("platform_id") REFERENCES "platforms" ("id");

ALTER TABLE "player_profiles" ADD FOREIGN KEY ("player_id") REFERENCES "players" ("id");

ALTER TABLE "player_profiles" ADD FOREIGN KEY ("avatar_item_id") REFERENCES "items" ("id");

ALTER TABLE "player_profiles" ADD FOREIGN KEY ("banner_item_id") REFERENCES "items" ("id");

ALTER TABLE "player_profiles" ADD FOREIGN KEY ("title_achievement_id") REFERENCES "achievements" ("id");

ALTER TABLE "wallet_ledger_entries" ADD FOREIGN KEY ("player_id") REFERENCES "players" ("id");

ALTER TABLE "wallet_ledger_entries" ADD FOREIGN KEY ("currency_id") REFERENCES "currencies" ("id");

ALTER TABLE "wallet_ledger_entries" ADD FOREIGN KEY ("purchase_id") REFERENCES "purchases" ("id");

ALTER TABLE "wallet_ledger_entries" ADD FOREIGN KEY ("match_id") REFERENCES "matches" ("id");

ALTER TABLE "wallet_ledger_entries" ADD FOREIGN KEY ("achievement_id") REFERENCES "achievements" ("id");

ALTER TABLE "wallet_ledger_entries" ADD FOREIGN KEY ("staff_account_id") REFERENCES "staff_accounts" ("id");

ALTER TABLE "inventory_items" ADD FOREIGN KEY ("player_id") REFERENCES "players" ("id");

ALTER TABLE "inventory_items" ADD FOREIGN KEY ("item_id") REFERENCES "items" ("id");

ALTER TABLE "inventory_items" ADD FOREIGN KEY ("purchase_id") REFERENCES "purchases" ("id");

ALTER TABLE "inventory_items" ADD FOREIGN KEY ("match_id") REFERENCES "matches" ("id");

ALTER TABLE "inventory_items" ADD FOREIGN KEY ("achievement_id") REFERENCES "achievements" ("id");

ALTER TABLE "store_offers" ADD FOREIGN KEY ("price_currency_id") REFERENCES "currencies" ("id");

ALTER TABLE "offer_contents" ADD FOREIGN KEY ("store_offer_id") REFERENCES "store_offers" ("id");

ALTER TABLE "offer_contents" ADD FOREIGN KEY ("item_id") REFERENCES "items" ("id");

ALTER TABLE "offer_contents" ADD FOREIGN KEY ("currency_id") REFERENCES "currencies" ("id");

ALTER TABLE "purchases" ADD FOREIGN KEY ("player_id") REFERENCES "players" ("id");

ALTER TABLE "purchases" ADD FOREIGN KEY ("store_offer_id") REFERENCES "store_offers" ("id");

ALTER TABLE "purchases" ADD FOREIGN KEY ("platform_id") REFERENCES "platforms" ("id");

ALTER TABLE "matchmaking_tickets" ADD FOREIGN KEY ("player_id") REFERENCES "players" ("id");

ALTER TABLE "matchmaking_tickets" ADD FOREIGN KEY ("party_id") REFERENCES "parties" ("id");

ALTER TABLE "matchmaking_tickets" ADD FOREIGN KEY ("game_mode_id") REFERENCES "game_modes" ("id");

ALTER TABLE "matchmaking_tickets" ADD FOREIGN KEY ("match_id") REFERENCES "matches" ("id");

ALTER TABLE "matches" ADD FOREIGN KEY ("game_mode_id") REFERENCES "game_modes" ("id");

ALTER TABLE "matches" ADD FOREIGN KEY ("season_id") REFERENCES "seasons" ("id");

ALTER TABLE "match_participants" ADD FOREIGN KEY ("match_id") REFERENCES "matches" ("id");

ALTER TABLE "match_participants" ADD FOREIGN KEY ("player_id") REFERENCES "players" ("id");

ALTER TABLE "match_participants" ADD FOREIGN KEY ("party_id") REFERENCES "parties" ("id");

ALTER TABLE "rating_events" ADD FOREIGN KEY ("player_id") REFERENCES "players" ("id");

ALTER TABLE "rating_events" ADD FOREIGN KEY ("game_mode_id") REFERENCES "game_modes" ("id");

ALTER TABLE "rating_events" ADD FOREIGN KEY ("season_id") REFERENCES "seasons" ("id");

ALTER TABLE "rating_events" ADD FOREIGN KEY ("match_id") REFERENCES "matches" ("id");

ALTER TABLE "player_ratings" ADD FOREIGN KEY ("player_id") REFERENCES "players" ("id");

ALTER TABLE "player_ratings" ADD FOREIGN KEY ("game_mode_id") REFERENCES "game_modes" ("id");

ALTER TABLE "player_ratings" ADD FOREIGN KEY ("season_id") REFERENCES "seasons" ("id");

ALTER TABLE "player_ratings" ADD FOREIGN KEY ("last_rating_event_id") REFERENCES "rating_events" ("id");

ALTER TABLE "leaderboard_snapshots" ADD FOREIGN KEY ("game_mode_id") REFERENCES "game_modes" ("id");

ALTER TABLE "leaderboard_snapshots" ADD FOREIGN KEY ("season_id") REFERENCES "seasons" ("id");

ALTER TABLE "leaderboard_entries" ADD FOREIGN KEY ("snapshot_id") REFERENCES "leaderboard_snapshots" ("id");

ALTER TABLE "leaderboard_entries" ADD FOREIGN KEY ("player_id") REFERENCES "players" ("id");

ALTER TABLE "achievements" ADD FOREIGN KEY ("reward_item_id") REFERENCES "items" ("id");

ALTER TABLE "achievements" ADD FOREIGN KEY ("reward_currency_id") REFERENCES "currencies" ("id");

ALTER TABLE "player_achievements" ADD FOREIGN KEY ("player_id") REFERENCES "players" ("id");

ALTER TABLE "player_achievements" ADD FOREIGN KEY ("achievement_id") REFERENCES "achievements" ("id");

ALTER TABLE "friendships" ADD FOREIGN KEY ("player_low_id") REFERENCES "players" ("id");

ALTER TABLE "friendships" ADD FOREIGN KEY ("player_high_id") REFERENCES "players" ("id");

ALTER TABLE "friendships" ADD FOREIGN KEY ("requested_by") REFERENCES "players" ("id");

ALTER TABLE "parties" ADD FOREIGN KEY ("leader_id") REFERENCES "players" ("id");

ALTER TABLE "parties" ADD FOREIGN KEY ("game_mode_id") REFERENCES "game_modes" ("id");

ALTER TABLE "party_members" ADD FOREIGN KEY ("party_id") REFERENCES "parties" ("id");

ALTER TABLE "party_members" ADD FOREIGN KEY ("player_id") REFERENCES "players" ("id");

ALTER TABLE "guild_members" ADD FOREIGN KEY ("guild_id") REFERENCES "guilds" ("id");

ALTER TABLE "guild_members" ADD FOREIGN KEY ("player_id") REFERENCES "players" ("id");

ALTER TABLE "player_reports" ADD FOREIGN KEY ("reporter_id") REFERENCES "players" ("id");

ALTER TABLE "player_reports" ADD FOREIGN KEY ("reported_player_id") REFERENCES "players" ("id");

ALTER TABLE "player_reports" ADD FOREIGN KEY ("match_id") REFERENCES "matches" ("id");

ALTER TABLE "player_reports" ADD FOREIGN KEY ("reviewed_by") REFERENCES "staff_accounts" ("id");

ALTER TABLE "player_reports" ADD FOREIGN KEY ("sanction_id") REFERENCES "sanctions" ("id");

ALTER TABLE "sanctions" ADD FOREIGN KEY ("player_id") REFERENCES "players" ("id");

ALTER TABLE "sanctions" ADD FOREIGN KEY ("issued_by") REFERENCES "staff_accounts" ("id");

ALTER TABLE "sanctions" ADD FOREIGN KEY ("evidence_match_id") REFERENCES "matches" ("id");

ALTER TABLE "sanctions" ADD FOREIGN KEY ("revoked_by") REFERENCES "staff_accounts" ("id");
MySQL
mysql.sql MySQL
CREATE TABLE `platforms` (
  `id` uuid PRIMARY KEY,
  `code` varchar(30) UNIQUE NOT NULL COMMENT 'Your own short code per integration, e.g. pc_store_a, console_b, mobile_store_a',
  `name` varchar(100) NOT NULL,
  `kind` ENUM ('pc', 'console', 'mobile', 'web') NOT NULL,
  `has_store` boolean NOT NULL DEFAULT true COMMENT 'Whether purchases can arrive with a receipt from this platform'
);

CREATE TABLE `players` (
  `id` uuid PRIMARY KEY,
  `display_name` varchar(32) NOT NULL,
  `name_tag` char(4) NOT NULL COMMENT 'Four-digit suffix, so display names need not be unique: "Raven#4821"',
  `country` char(2),
  `status` ENUM ('active', 'suspended', 'banned', 'deleted') NOT NULL DEFAULT 'active' COMMENT 'CACHE of active sanctions, refreshed when one starts, expires or is revoked',
  `created_at` timestamptz NOT NULL DEFAULT (now()),
  `last_login_at` timestamptz,
  `deleted_at` timestamptz COMMENT 'Soft delete for data-deletion requests. Ledger rows stay, keyed by an id that no longer identifies anyone'
);

CREATE TABLE `platform_identities` (
  `id` uuid PRIMARY KEY,
  `player_id` uuid NOT NULL,
  `platform_id` uuid NOT NULL,
  `external_user_id` varchar(128) NOT NULL COMMENT 'The account id the platform hands over after sign-in',
  `external_display_name` varchar(100),
  `linked_at` timestamptz NOT NULL DEFAULT (now()),
  `last_auth_at` timestamptz,
  `unlinked_at` timestamptz
);

CREATE TABLE `player_profiles` (
  `player_id` uuid PRIMARY KEY,
  `avatar_item_id` uuid COMMENT 'An equipped cosmetic must be owned: checked against inventory on equip',
  `banner_item_id` uuid,
  `title_achievement_id` uuid COMMENT 'A display title unlocked by an achievement',
  `account_level` integer NOT NULL DEFAULT 1,
  `account_xp` bigint NOT NULL DEFAULT 0,
  `show_online_status` boolean NOT NULL DEFAULT true,
  `updated_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `currencies` (
  `id` uuid PRIMARY KEY,
  `code` varchar(10) UNIQUE NOT NULL COMMENT 'e.g. GOLD (soft), GEMS (premium)',
  `name` varchar(60) NOT NULL,
  `kind` ENUM ('soft', 'premium', 'event') NOT NULL,
  `max_balance` bigint COMMENT 'Cap enforced when a credit is written; null for no cap',
  `is_purchasable` boolean NOT NULL DEFAULT false COMMENT 'Only premium currency is sold for real money'
);

CREATE TABLE `wallet_ledger_entries` (
  `id` uuid PRIMARY KEY,
  `player_id` uuid NOT NULL,
  `currency_id` uuid NOT NULL,
  `sequence` bigint NOT NULL COMMENT 'Per player and currency: 1, 2, 3 with no gaps',
  `amount` bigint NOT NULL COMMENT 'Signed: a credit is positive, a debit negative. Never zero',
  `balance_after` bigint NOT NULL COMMENT 'Running balance, computed at insert from the previous row (locked FOR UPDATE). A CHECK keeps it at or above zero',
  `reason` ENUM ('purchase_credit', 'store_spend', 'match_reward', 'achievement_reward', 'season_reward', 'refund_reversal', 'chargeback_reversal', 'admin_adjustment', 'expiry') NOT NULL,
  `purchase_id` uuid,
  `match_id` uuid,
  `achievement_id` uuid,
  `staff_account_id` uuid COMMENT 'Required for admin adjustments, so an insider grant is always attributed',
  `idempotency_key` varchar(100) UNIQUE NOT NULL COMMENT 'e.g. purchase:<id>:credit or match:<id>:reward. A retried grant collides here instead of paying twice',
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `items` (
  `id` uuid PRIMARY KEY,
  `sku` varchar(60) UNIQUE NOT NULL,
  `name` varchar(120) NOT NULL,
  `kind` ENUM ('character', 'skin', 'weapon', 'emote', 'avatar', 'banner', 'consumable', 'boost') NOT NULL,
  `rarity` ENUM ('common', 'uncommon', 'rare', 'epic', 'legendary') NOT NULL,
  `is_stackable` boolean NOT NULL DEFAULT false COMMENT 'Consumables stack into one inventory row with a quantity',
  `is_tradeable` boolean NOT NULL DEFAULT false,
  `released_at` timestamptz,
  `retired_at` timestamptz COMMENT 'No longer obtainable. Owned copies are kept'
);

CREATE TABLE `inventory_items` (
  `id` uuid PRIMARY KEY,
  `player_id` uuid NOT NULL,
  `item_id` uuid NOT NULL,
  `quantity` integer NOT NULL DEFAULT 1 COMMENT 'Remaining uses for stackable consumables; 1 for everything else',
  `grant_reason` ENUM ('purchase', 'match_reward', 'achievement', 'season_reward', 'starter', 'admin_grant') NOT NULL,
  `purchase_id` uuid,
  `match_id` uuid,
  `achievement_id` uuid,
  `granted_at` timestamptz NOT NULL DEFAULT (now()),
  `expires_at` timestamptz COMMENT 'Rentals and time-limited boosts',
  `revoked_at` timestamptz COMMENT 'Set by a refund or chargeback. The row stays as evidence'
);

CREATE TABLE `store_offers` (
  `id` uuid PRIMARY KEY,
  `sku` varchar(60) UNIQUE NOT NULL,
  `name` varchar(120) NOT NULL,
  `price_kind` ENUM ('real_money', 'virtual_currency') NOT NULL,
  `price_currency_id` uuid COMMENT 'Set when priced in a virtual currency',
  `price_amount` bigint COMMENT 'In units of price_currency_id',
  `platform_product_id` varchar(100) COMMENT 'Set when priced in real money: the product id configured in each platform store. Real prices live in the store, not here',
  `starts_at` timestamptz,
  `ends_at` timestamptz COMMENT 'Limited-time offers',
  `max_per_player` integer COMMENT 'e.g. 1 for a starter pack',
  `is_active` boolean NOT NULL DEFAULT true
);

CREATE TABLE `offer_contents` (
  `id` uuid PRIMARY KEY,
  `store_offer_id` uuid NOT NULL,
  `item_id` uuid,
  `currency_id` uuid,
  `quantity` bigint NOT NULL
);

CREATE TABLE `purchases` (
  `id` uuid PRIMARY KEY,
  `player_id` uuid NOT NULL,
  `store_offer_id` uuid NOT NULL,
  `platform_id` uuid COMMENT 'Null for purchases paid in virtual currency',
  `platform_transaction_id` varchar(200) COMMENT 'The receipt or order id issued by the platform store',
  `receipt_payload` text COMMENT 'Raw receipt as received, kept for disputes and re-validation',
  `status` ENUM ('pending_validation', 'validated', 'fulfilled', 'rejected', 'refunded', 'chargeback') NOT NULL DEFAULT 'pending_validation',
  `price_cents` integer COMMENT 'Real-money amount as reported by the store',
  `currency` char(3),
  `created_at` timestamptz NOT NULL DEFAULT (now()),
  `validated_at` timestamptz,
  `fulfilled_at` timestamptz,
  `refunded_at` timestamptz
);

CREATE TABLE `seasons` (
  `id` uuid PRIMARY KEY,
  `number` integer UNIQUE NOT NULL,
  `name` varchar(100) NOT NULL,
  `starts_at` timestamptz NOT NULL,
  `ends_at` timestamptz NOT NULL,
  `soft_reset_factor` numeric(3,2) NOT NULL DEFAULT 0.5 COMMENT 'How far ratings are pulled toward the mean at season start'
);

CREATE TABLE `game_modes` (
  `id` uuid PRIMARY KEY,
  `code` varchar(30) UNIQUE NOT NULL COMMENT 'e.g. ranked_5v5, casual_ffa',
  `name` varchar(100) NOT NULL,
  `team_count` smallint NOT NULL,
  `team_size` smallint NOT NULL,
  `is_ranked` boolean NOT NULL DEFAULT false,
  `is_active` boolean NOT NULL DEFAULT true
);

CREATE TABLE `matchmaking_tickets` (
  `id` uuid PRIMARY KEY,
  `player_id` uuid NOT NULL COMMENT 'The player who queued; for a party, its leader',
  `party_id` uuid,
  `game_mode_id` uuid NOT NULL,
  `region` varchar(20) NOT NULL COMMENT 'e.g. eu-west, us-east',
  `rating_at_queue` integer NOT NULL COMMENT 'Snapshot used for matching; a party queues on a combined rating',
  `latency_ms` jsonb COMMENT 'Measured ping per region, e.g. {"eu-west": 31, "us-east": 104}',
  `status` ENUM ('queued', 'matched', 'cancelled', 'timed_out') NOT NULL DEFAULT 'queued',
  `created_at` timestamptz NOT NULL DEFAULT (now()),
  `matched_at` timestamptz,
  `match_id` uuid
);

CREATE TABLE `matches` (
  `id` uuid PRIMARY KEY,
  `game_mode_id` uuid NOT NULL,
  `season_id` uuid,
  `region` varchar(20) NOT NULL,
  `server_id` varchar(100) COMMENT 'Allocated dedicated server or session host',
  `server_build` varchar(40) COMMENT 'Game server version, for when a bug invalidates every match played on one build',
  `status` ENUM ('allocating', 'in_progress', 'completed', 'abandoned', 'invalidated') NOT NULL DEFAULT 'allocating',
  `started_at` timestamptz,
  `ended_at` timestamptz,
  `winning_team` smallint
);

CREATE TABLE `match_participants` (
  `match_id` uuid NOT NULL,
  `player_id` uuid NOT NULL,
  `team` smallint NOT NULL,
  `party_id` uuid,
  `outcome` ENUM ('win', 'loss', 'draw', 'abandoned'),
  `placement` smallint COMMENT 'Finishing position, for free-for-all modes',
  `score` integer,
  `stats` jsonb COMMENT 'Mode-specific numbers, e.g. kills, assists, objectives',
  `joined_at` timestamptz NOT NULL,
  `left_at` timestamptz COMMENT 'Earlier than the match end means the player left early',
  PRIMARY KEY (`match_id`, `player_id`)
);

CREATE TABLE `rating_events` (
  `id` uuid PRIMARY KEY,
  `player_id` uuid NOT NULL,
  `game_mode_id` uuid NOT NULL,
  `season_id` uuid NOT NULL,
  `match_id` uuid COMMENT 'Null for season resets and decay',
  `kind` ENUM ('match', 'season_reset', 'decay', 'correction') NOT NULL,
  `rating_before` integer NOT NULL,
  `rating_after` integer NOT NULL,
  `uncertainty_after` numeric(6,2) COMMENT 'Rating deviation, for systems that track confidence as well as skill',
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `player_ratings` (
  `player_id` uuid NOT NULL,
  `game_mode_id` uuid NOT NULL,
  `season_id` uuid NOT NULL,
  `rating` integer NOT NULL,
  `uncertainty` numeric(6,2),
  `games_played` integer NOT NULL DEFAULT 0,
  `wins` integer NOT NULL DEFAULT 0,
  `last_rating_event_id` uuid NOT NULL COMMENT 'The event this cache was built from',
  `updated_at` timestamptz NOT NULL,
  PRIMARY KEY (`player_id`, `game_mode_id`, `season_id`)
);

CREATE TABLE `leaderboard_snapshots` (
  `id` uuid PRIMARY KEY,
  `game_mode_id` uuid NOT NULL,
  `season_id` uuid NOT NULL,
  `region` varchar(20) COMMENT 'Null for the global board',
  `taken_at` timestamptz NOT NULL,
  `is_final` boolean NOT NULL DEFAULT false COMMENT 'The end-of-season board that season rewards are paid from'
);

CREATE TABLE `leaderboard_entries` (
  `snapshot_id` uuid NOT NULL,
  `rank` integer NOT NULL COMMENT 'Ties broken by who reached the rating first',
  `player_id` uuid NOT NULL,
  `rating` integer NOT NULL,
  `display_name` varchar(40) NOT NULL COMMENT 'Copied at snapshot time, so the board reads without a join and shows the name used then',
  PRIMARY KEY (`snapshot_id`, `rank`)
);

CREATE TABLE `achievements` (
  `id` uuid PRIMARY KEY,
  `code` varchar(60) UNIQUE NOT NULL,
  `name` varchar(120) NOT NULL,
  `description` varchar(500) NOT NULL,
  `target_value` integer NOT NULL DEFAULT 1 COMMENT 'e.g. 100 for "win 100 ranked matches"',
  `is_hidden` boolean NOT NULL DEFAULT false COMMENT 'Secret until unlocked',
  `reward_item_id` uuid,
  `reward_currency_id` uuid,
  `reward_amount` bigint
);

CREATE TABLE `player_achievements` (
  `player_id` uuid NOT NULL,
  `achievement_id` uuid NOT NULL,
  `progress` integer NOT NULL DEFAULT 0,
  `completed_at` timestamptz,
  `reward_claimed_at` timestamptz COMMENT 'Claiming writes the ledger or inventory row; its idempotency key stops a double claim',
  `updated_at` timestamptz NOT NULL,
  PRIMARY KEY (`player_id`, `achievement_id`)
);

CREATE TABLE `friendships` (
  `player_low_id` uuid NOT NULL COMMENT 'The smaller of the two ids (CHECK player_low_id < player_high_id)',
  `player_high_id` uuid NOT NULL,
  `requested_by` uuid NOT NULL,
  `status` ENUM ('pending', 'accepted') NOT NULL DEFAULT 'pending',
  `created_at` timestamptz NOT NULL DEFAULT (now()),
  `accepted_at` timestamptz,
  PRIMARY KEY (`player_low_id`, `player_high_id`)
);

CREATE TABLE `parties` (
  `id` uuid PRIMARY KEY,
  `leader_id` uuid NOT NULL,
  `game_mode_id` uuid COMMENT 'What the party is about to queue for',
  `max_size` smallint NOT NULL,
  `invite_code` varchar(12) UNIQUE,
  `created_at` timestamptz NOT NULL DEFAULT (now()),
  `disbanded_at` timestamptz
);

CREATE TABLE `party_members` (
  `party_id` uuid NOT NULL,
  `player_id` uuid NOT NULL,
  `joined_at` timestamptz NOT NULL DEFAULT (now()),
  `left_at` timestamptz,
  PRIMARY KEY (`party_id`, `player_id`)
);

CREATE TABLE `guilds` (
  `id` uuid PRIMARY KEY,
  `name` varchar(50) UNIQUE NOT NULL,
  `tag` varchar(5) UNIQUE NOT NULL COMMENT 'Short tag shown beside member names, e.g. [ABC]',
  `description` varchar(500),
  `member_limit` smallint NOT NULL DEFAULT 50,
  `is_open` boolean NOT NULL DEFAULT false COMMENT 'Open guilds accept joins without an invite',
  `created_at` timestamptz NOT NULL DEFAULT (now()),
  `disbanded_at` timestamptz
);

CREATE TABLE `guild_members` (
  `id` uuid PRIMARY KEY,
  `guild_id` uuid NOT NULL,
  `player_id` uuid NOT NULL,
  `role` ENUM ('leader', 'officer', 'member', 'recruit') NOT NULL DEFAULT 'member',
  `joined_at` timestamptz NOT NULL DEFAULT (now()),
  `left_at` timestamptz,
  `left_reason` ENUM ('left', 'kicked', 'guild_disbanded')
);

CREATE TABLE `staff_accounts` (
  `id` uuid PRIMARY KEY,
  `email` varchar(254) UNIQUE NOT NULL,
  `name` varchar(120) NOT NULL,
  `role` ENUM ('support', 'moderator', 'live_ops', 'admin') NOT NULL,
  `disabled_at` timestamptz
);

CREATE TABLE `player_reports` (
  `id` uuid PRIMARY KEY,
  `reporter_id` uuid NOT NULL,
  `reported_player_id` uuid NOT NULL,
  `match_id` uuid COMMENT 'The match it happened in, so a reviewer can pull the replay',
  `reason` ENUM ('cheating', 'griefing', 'abusive_chat', 'offensive_name', 'win_trading', 'account_sharing', 'other') NOT NULL,
  `details` varchar(1000),
  `created_at` timestamptz NOT NULL DEFAULT (now()),
  `reviewed_at` timestamptz,
  `reviewed_by` uuid,
  `sanction_id` uuid COMMENT 'The sanction it led to, if any'
);

CREATE TABLE `sanctions` (
  `id` uuid PRIMARY KEY,
  `player_id` uuid NOT NULL,
  `kind` ENUM ('warning', 'chat_mute', 'matchmaking_cooldown', 'ranked_ban', 'temporary_ban', 'permanent_ban') NOT NULL,
  `reason` ENUM ('cheating', 'griefing', 'abusive_chat', 'offensive_name', 'win_trading', 'account_sharing', 'other') NOT NULL,
  `details` text,
  `issued_by` uuid COMMENT 'Null for automated systems such as anti-cheat',
  `evidence_match_id` uuid,
  `starts_at` timestamptz NOT NULL DEFAULT (now()),
  `expires_at` timestamptz COMMENT 'Null for permanent',
  `revoked_at` timestamptz COMMENT 'Overturned on appeal. The row stays',
  `revoked_by` uuid,
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE UNIQUE INDEX `players_index_0` ON `players` (`display_name`, `name_tag`);

CREATE INDEX `platform_identities_index_1` ON `platform_identities` (`platform_id`, `external_user_id`);

CREATE INDEX `platform_identities_index_2` ON `platform_identities` (`player_id`);

CREATE UNIQUE INDEX `wallet_ledger_entries_index_3` ON `wallet_ledger_entries` (`player_id`, `currency_id`, `sequence`);

CREATE INDEX `inventory_items_index_4` ON `inventory_items` (`player_id`, `item_id`);

CREATE UNIQUE INDEX `purchases_index_5` ON `purchases` (`platform_id`, `platform_transaction_id`);

CREATE INDEX `purchases_index_6` ON `purchases` (`player_id`, `created_at`);

CREATE INDEX `matchmaking_tickets_index_7` ON `matchmaking_tickets` (`game_mode_id`, `region`, `status`, `created_at`);

CREATE INDEX `match_participants_index_8` ON `match_participants` (`player_id`, `joined_at`);

CREATE INDEX `rating_events_index_9` ON `rating_events` (`player_id`, `game_mode_id`, `season_id`, `created_at`);

CREATE UNIQUE INDEX `rating_events_index_10` ON `rating_events` (`player_id`, `match_id`, `kind`);

CREATE INDEX `player_ratings_index_11` ON `player_ratings` (`game_mode_id`, `season_id`, `rating`);

CREATE UNIQUE INDEX `leaderboard_entries_index_12` ON `leaderboard_entries` (`snapshot_id`, `player_id`);

CREATE INDEX `friendships_index_13` ON `friendships` (`player_high_id`);

CREATE INDEX `party_members_index_14` ON `party_members` (`player_id`);

CREATE INDEX `guild_members_index_15` ON `guild_members` (`player_id`);

CREATE INDEX `guild_members_index_16` ON `guild_members` (`guild_id`, `role`);

CREATE INDEX `player_reports_index_17` ON `player_reports` (`reported_player_id`, `created_at`);

CREATE INDEX `sanctions_index_18` ON `sanctions` (`player_id`, `expires_at`);

ALTER TABLE `platforms` COMMENT = 'Storefronts, console networks and mobile app stores the game ships on. Platforms are data, not schema, so adding one is an INSERT.';

ALTER TABLE `players` COMMENT = 'The game account, independent of any platform. Wallet, inventory and ratings hang off this id, which is what makes cross-progression possible.';

ALTER TABLE `platform_identities` COMMENT = 'Linked platform accounts. Sign-in looks up (platform, external id) to find the player; a player on three platforms has three rows.';

ALTER TABLE `player_profiles` COMMENT = 'What other players see: equipped cosmetics, title and level. Split from players so a busy profile never locks the account row.';

ALTER TABLE `currencies` COMMENT = 'Virtual currencies. Premium currency is bought, so it carries refund and chargeback obligations that soft currency does not.';

ALTER TABLE `wallet_ledger_entries` COMMENT = 'The wallet. There is no balance column anywhere to UPDATE: every change to every currency is an insert here, with its cause. A duplication exploit shows up as rows with a reason, and any balance can be recomputed from history.';

ALTER TABLE `items` COMMENT = 'The item catalog: everything a player can own.';

ALTER TABLE `inventory_items` COMMENT = 'Item instances a player owns, each pointing at whatever granted it. Revoking is a timestamp, so support can always answer "where did this come from?"';

ALTER TABLE `store_offers` COMMENT = 'What the in-game store sells: a bundle of contents for one price, in real money or a virtual currency.';

ALTER TABLE `offer_contents` COMMENT = 'What an offer grants. Exactly one of item_id and currency_id per row, so a gem pack is just an offer whose only content is currency.';

ALTER TABLE `purchases` COMMENT = 'Every purchase, as a state machine: validate the receipt server-side with the platform, then fulfil by writing ledger and inventory rows keyed on this id. Never trust a client that says it paid.';

ALTER TABLE `seasons` COMMENT = 'Competitive seasons. Ratings and leaderboards are scoped to one.';

ALTER TABLE `game_modes` COMMENT = 'Playlists. A rating only means something within one mode, so ratings are keyed by it.';

ALTER TABLE `matchmaking_tickets` COMMENT = 'A request to play. Kept after matching, so time-to-match and abandoned queues can be measured.';

ALTER TABLE `matches` COMMENT = 'One played game, with results written by the authoritative server, never by a client. An invalidated match keeps its row but pays no rewards and moves no ratings.';

ALTER TABLE `match_participants` COMMENT = 'Who played, on which team, and how it went for them. Rewards and rating changes are computed from these rows.';

ALTER TABLE `rating_events` COMMENT = 'Append-only MMR history per player, per mode, per season. Undoing the games lost to a banned cheater is a new correction row, never an edit.';

ALTER TABLE `player_ratings` COMMENT = 'CACHE of the latest rating_events row, for the matchmaker and the profile. Rebuildable from history at any time.';

ALTER TABLE `leaderboard_snapshots` COMMENT = 'A leaderboard frozen at a moment, e.g. every 15 minutes. Readers page through a snapshot instead of sorting a live table, and the final one is the permanent record.';

ALTER TABLE `leaderboard_entries` COMMENT = 'The ranked rows of a snapshot. Usually only the top few thousand are stored.';

ALTER TABLE `achievements` COMMENT = 'Achievement definitions and what they pay out.';

ALTER TABLE `player_achievements` COMMENT = 'Progress toward each achievement, created on first progress.';

ALTER TABLE `friendships` COMMENT = 'Mutual friendships stored once, as an ordered pair, so A-B and B-A can never both exist. A friends list reads both columns.';

ALTER TABLE `parties` COMMENT = 'A group that queues together. Short-lived, but kept for match history and for spotting win-trading groups.';

ALTER TABLE `party_members` COMMENT = 'Who is, or was, in a party.';

ALTER TABLE `guilds` COMMENT = 'Long-lived player organizations: guilds, clans, crews.';

ALTER TABLE `guild_members` COMMENT = 'Membership history with roles. Leadership is a role, not a column on guilds, so a handover is two updates in one transaction.';

ALTER TABLE `staff_accounts` COMMENT = 'Support agents, moderators and live-ops staff. Kept apart from players: staff never act through a game account.';

ALTER TABLE `player_reports` COMMENT = 'In-game reports. Volume per reported player feeds automated review; one report rarely decides anything alone.';

ALTER TABLE `sanctions` COMMENT = 'Warnings, chat mutes, queue cooldowns, ranked bans and account bans, each a row with a time window. A ban is a sanction, so its history and appeal live in one place; players.status only caches what is active.';

ALTER TABLE `platform_identities` ADD FOREIGN KEY (`player_id`) REFERENCES `players` (`id`);

ALTER TABLE `platform_identities` ADD FOREIGN KEY (`platform_id`) REFERENCES `platforms` (`id`);

ALTER TABLE `player_profiles` ADD FOREIGN KEY (`player_id`) REFERENCES `players` (`id`);

ALTER TABLE `player_profiles` ADD FOREIGN KEY (`avatar_item_id`) REFERENCES `items` (`id`);

ALTER TABLE `player_profiles` ADD FOREIGN KEY (`banner_item_id`) REFERENCES `items` (`id`);

ALTER TABLE `player_profiles` ADD FOREIGN KEY (`title_achievement_id`) REFERENCES `achievements` (`id`);

ALTER TABLE `wallet_ledger_entries` ADD FOREIGN KEY (`player_id`) REFERENCES `players` (`id`);

ALTER TABLE `wallet_ledger_entries` ADD FOREIGN KEY (`currency_id`) REFERENCES `currencies` (`id`);

ALTER TABLE `wallet_ledger_entries` ADD FOREIGN KEY (`purchase_id`) REFERENCES `purchases` (`id`);

ALTER TABLE `wallet_ledger_entries` ADD FOREIGN KEY (`match_id`) REFERENCES `matches` (`id`);

ALTER TABLE `wallet_ledger_entries` ADD FOREIGN KEY (`achievement_id`) REFERENCES `achievements` (`id`);

ALTER TABLE `wallet_ledger_entries` ADD FOREIGN KEY (`staff_account_id`) REFERENCES `staff_accounts` (`id`);

ALTER TABLE `inventory_items` ADD FOREIGN KEY (`player_id`) REFERENCES `players` (`id`);

ALTER TABLE `inventory_items` ADD FOREIGN KEY (`item_id`) REFERENCES `items` (`id`);

ALTER TABLE `inventory_items` ADD FOREIGN KEY (`purchase_id`) REFERENCES `purchases` (`id`);

ALTER TABLE `inventory_items` ADD FOREIGN KEY (`match_id`) REFERENCES `matches` (`id`);

ALTER TABLE `inventory_items` ADD FOREIGN KEY (`achievement_id`) REFERENCES `achievements` (`id`);

ALTER TABLE `store_offers` ADD FOREIGN KEY (`price_currency_id`) REFERENCES `currencies` (`id`);

ALTER TABLE `offer_contents` ADD FOREIGN KEY (`store_offer_id`) REFERENCES `store_offers` (`id`);

ALTER TABLE `offer_contents` ADD FOREIGN KEY (`item_id`) REFERENCES `items` (`id`);

ALTER TABLE `offer_contents` ADD FOREIGN KEY (`currency_id`) REFERENCES `currencies` (`id`);

ALTER TABLE `purchases` ADD FOREIGN KEY (`player_id`) REFERENCES `players` (`id`);

ALTER TABLE `purchases` ADD FOREIGN KEY (`store_offer_id`) REFERENCES `store_offers` (`id`);

ALTER TABLE `purchases` ADD FOREIGN KEY (`platform_id`) REFERENCES `platforms` (`id`);

ALTER TABLE `matchmaking_tickets` ADD FOREIGN KEY (`player_id`) REFERENCES `players` (`id`);

ALTER TABLE `matchmaking_tickets` ADD FOREIGN KEY (`party_id`) REFERENCES `parties` (`id`);

ALTER TABLE `matchmaking_tickets` ADD FOREIGN KEY (`game_mode_id`) REFERENCES `game_modes` (`id`);

ALTER TABLE `matchmaking_tickets` ADD FOREIGN KEY (`match_id`) REFERENCES `matches` (`id`);

ALTER TABLE `matches` ADD FOREIGN KEY (`game_mode_id`) REFERENCES `game_modes` (`id`);

ALTER TABLE `matches` ADD FOREIGN KEY (`season_id`) REFERENCES `seasons` (`id`);

ALTER TABLE `match_participants` ADD FOREIGN KEY (`match_id`) REFERENCES `matches` (`id`);

ALTER TABLE `match_participants` ADD FOREIGN KEY (`player_id`) REFERENCES `players` (`id`);

ALTER TABLE `match_participants` ADD FOREIGN KEY (`party_id`) REFERENCES `parties` (`id`);

ALTER TABLE `rating_events` ADD FOREIGN KEY (`player_id`) REFERENCES `players` (`id`);

ALTER TABLE `rating_events` ADD FOREIGN KEY (`game_mode_id`) REFERENCES `game_modes` (`id`);

ALTER TABLE `rating_events` ADD FOREIGN KEY (`season_id`) REFERENCES `seasons` (`id`);

ALTER TABLE `rating_events` ADD FOREIGN KEY (`match_id`) REFERENCES `matches` (`id`);

ALTER TABLE `player_ratings` ADD FOREIGN KEY (`player_id`) REFERENCES `players` (`id`);

ALTER TABLE `player_ratings` ADD FOREIGN KEY (`game_mode_id`) REFERENCES `game_modes` (`id`);

ALTER TABLE `player_ratings` ADD FOREIGN KEY (`season_id`) REFERENCES `seasons` (`id`);

ALTER TABLE `player_ratings` ADD FOREIGN KEY (`last_rating_event_id`) REFERENCES `rating_events` (`id`);

ALTER TABLE `leaderboard_snapshots` ADD FOREIGN KEY (`game_mode_id`) REFERENCES `game_modes` (`id`);

ALTER TABLE `leaderboard_snapshots` ADD FOREIGN KEY (`season_id`) REFERENCES `seasons` (`id`);

ALTER TABLE `leaderboard_entries` ADD FOREIGN KEY (`snapshot_id`) REFERENCES `leaderboard_snapshots` (`id`);

ALTER TABLE `leaderboard_entries` ADD FOREIGN KEY (`player_id`) REFERENCES `players` (`id`);

ALTER TABLE `achievements` ADD FOREIGN KEY (`reward_item_id`) REFERENCES `items` (`id`);

ALTER TABLE `achievements` ADD FOREIGN KEY (`reward_currency_id`) REFERENCES `currencies` (`id`);

ALTER TABLE `player_achievements` ADD FOREIGN KEY (`player_id`) REFERENCES `players` (`id`);

ALTER TABLE `player_achievements` ADD FOREIGN KEY (`achievement_id`) REFERENCES `achievements` (`id`);

ALTER TABLE `friendships` ADD FOREIGN KEY (`player_low_id`) REFERENCES `players` (`id`);

ALTER TABLE `friendships` ADD FOREIGN KEY (`player_high_id`) REFERENCES `players` (`id`);

ALTER TABLE `friendships` ADD FOREIGN KEY (`requested_by`) REFERENCES `players` (`id`);

ALTER TABLE `parties` ADD FOREIGN KEY (`leader_id`) REFERENCES `players` (`id`);

ALTER TABLE `parties` ADD FOREIGN KEY (`game_mode_id`) REFERENCES `game_modes` (`id`);

ALTER TABLE `party_members` ADD FOREIGN KEY (`party_id`) REFERENCES `parties` (`id`);

ALTER TABLE `party_members` ADD FOREIGN KEY (`player_id`) REFERENCES `players` (`id`);

ALTER TABLE `guild_members` ADD FOREIGN KEY (`guild_id`) REFERENCES `guilds` (`id`);

ALTER TABLE `guild_members` ADD FOREIGN KEY (`player_id`) REFERENCES `players` (`id`);

ALTER TABLE `player_reports` ADD FOREIGN KEY (`reporter_id`) REFERENCES `players` (`id`);

ALTER TABLE `player_reports` ADD FOREIGN KEY (`reported_player_id`) REFERENCES `players` (`id`);

ALTER TABLE `player_reports` ADD FOREIGN KEY (`match_id`) REFERENCES `matches` (`id`);

ALTER TABLE `player_reports` ADD FOREIGN KEY (`reviewed_by`) REFERENCES `staff_accounts` (`id`);

ALTER TABLE `player_reports` ADD FOREIGN KEY (`sanction_id`) REFERENCES `sanctions` (`id`);

ALTER TABLE `sanctions` ADD FOREIGN KEY (`player_id`) REFERENCES `players` (`id`);

ALTER TABLE `sanctions` ADD FOREIGN KEY (`issued_by`) REFERENCES `staff_accounts` (`id`);

ALTER TABLE `sanctions` ADD FOREIGN KEY (`evidence_match_id`) REFERENCES `matches` (`id`);

ALTER TABLE `sanctions` ADD FOREIGN KEY (`revoked_by`) REFERENCES `staff_accounts` (`id`);
SQL Server
sql-server.sql SQL Server
CREATE TABLE [platforms] (
  [id] uuid PRIMARY KEY,
  [code] varchar(30) UNIQUE NOT NULL,
  [name] varchar(100) NOT NULL,
  [kind] nvarchar(255) NOT NULL CHECK ([kind] IN ('pc', 'console', 'mobile', 'web')),
  [has_store] boolean NOT NULL DEFAULT (true)
)
GO

CREATE TABLE [players] (
  [id] uuid PRIMARY KEY,
  [display_name] varchar(32) NOT NULL,
  [name_tag] char(4) NOT NULL,
  [country] char(2),
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('active', 'suspended', 'banned', 'deleted')) DEFAULT 'active',
  [created_at] timestamptz NOT NULL DEFAULT (now()),
  [last_login_at] timestamptz,
  [deleted_at] timestamptz
)
GO

CREATE TABLE [platform_identities] (
  [id] uuid PRIMARY KEY,
  [player_id] uuid NOT NULL,
  [platform_id] uuid NOT NULL,
  [external_user_id] varchar(128) NOT NULL,
  [external_display_name] varchar(100),
  [linked_at] timestamptz NOT NULL DEFAULT (now()),
  [last_auth_at] timestamptz,
  [unlinked_at] timestamptz
)
GO

CREATE TABLE [player_profiles] (
  [player_id] uuid PRIMARY KEY,
  [avatar_item_id] uuid,
  [banner_item_id] uuid,
  [title_achievement_id] uuid,
  [account_level] integer NOT NULL DEFAULT (1),
  [account_xp] bigint NOT NULL DEFAULT (0),
  [show_online_status] boolean NOT NULL DEFAULT (true),
  [updated_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [currencies] (
  [id] uuid PRIMARY KEY,
  [code] varchar(10) UNIQUE NOT NULL,
  [name] varchar(60) NOT NULL,
  [kind] nvarchar(255) NOT NULL CHECK ([kind] IN ('soft', 'premium', 'event')),
  [max_balance] bigint,
  [is_purchasable] boolean NOT NULL DEFAULT (false)
)
GO

CREATE TABLE [wallet_ledger_entries] (
  [id] uuid PRIMARY KEY,
  [player_id] uuid NOT NULL,
  [currency_id] uuid NOT NULL,
  [sequence] bigint NOT NULL,
  [amount] bigint NOT NULL,
  [balance_after] bigint NOT NULL,
  [reason] nvarchar(255) NOT NULL CHECK ([reason] IN ('purchase_credit', 'store_spend', 'match_reward', 'achievement_reward', 'season_reward', 'refund_reversal', 'chargeback_reversal', 'admin_adjustment', 'expiry')),
  [purchase_id] uuid,
  [match_id] uuid,
  [achievement_id] uuid,
  [staff_account_id] uuid,
  [idempotency_key] varchar(100) UNIQUE NOT NULL,
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [items] (
  [id] uuid PRIMARY KEY,
  [sku] varchar(60) UNIQUE NOT NULL,
  [name] varchar(120) NOT NULL,
  [kind] nvarchar(255) NOT NULL CHECK ([kind] IN ('character', 'skin', 'weapon', 'emote', 'avatar', 'banner', 'consumable', 'boost')),
  [rarity] nvarchar(255) NOT NULL CHECK ([rarity] IN ('common', 'uncommon', 'rare', 'epic', 'legendary')),
  [is_stackable] boolean NOT NULL DEFAULT (false),
  [is_tradeable] boolean NOT NULL DEFAULT (false),
  [released_at] timestamptz,
  [retired_at] timestamptz
)
GO

CREATE TABLE [inventory_items] (
  [id] uuid PRIMARY KEY,
  [player_id] uuid NOT NULL,
  [item_id] uuid NOT NULL,
  [quantity] integer NOT NULL DEFAULT (1),
  [grant_reason] nvarchar(255) NOT NULL CHECK ([grant_reason] IN ('purchase', 'match_reward', 'achievement', 'season_reward', 'starter', 'admin_grant')),
  [purchase_id] uuid,
  [match_id] uuid,
  [achievement_id] uuid,
  [granted_at] timestamptz NOT NULL DEFAULT (now()),
  [expires_at] timestamptz,
  [revoked_at] timestamptz
)
GO

CREATE TABLE [store_offers] (
  [id] uuid PRIMARY KEY,
  [sku] varchar(60) UNIQUE NOT NULL,
  [name] varchar(120) NOT NULL,
  [price_kind] nvarchar(255) NOT NULL CHECK ([price_kind] IN ('real_money', 'virtual_currency')),
  [price_currency_id] uuid,
  [price_amount] bigint,
  [platform_product_id] varchar(100),
  [starts_at] timestamptz,
  [ends_at] timestamptz,
  [max_per_player] integer,
  [is_active] boolean NOT NULL DEFAULT (true)
)
GO

CREATE TABLE [offer_contents] (
  [id] uuid PRIMARY KEY,
  [store_offer_id] uuid NOT NULL,
  [item_id] uuid,
  [currency_id] uuid,
  [quantity] bigint NOT NULL
)
GO

CREATE TABLE [purchases] (
  [id] uuid PRIMARY KEY,
  [player_id] uuid NOT NULL,
  [store_offer_id] uuid NOT NULL,
  [platform_id] uuid,
  [platform_transaction_id] varchar(200),
  [receipt_payload] text,
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('pending_validation', 'validated', 'fulfilled', 'rejected', 'refunded', 'chargeback')) DEFAULT 'pending_validation',
  [price_cents] integer,
  [currency] char(3),
  [created_at] timestamptz NOT NULL DEFAULT (now()),
  [validated_at] timestamptz,
  [fulfilled_at] timestamptz,
  [refunded_at] timestamptz
)
GO

CREATE TABLE [seasons] (
  [id] uuid PRIMARY KEY,
  [number] integer UNIQUE NOT NULL,
  [name] varchar(100) NOT NULL,
  [starts_at] timestamptz NOT NULL,
  [ends_at] timestamptz NOT NULL,
  [soft_reset_factor] numeric(3,2) NOT NULL DEFAULT (0.5)
)
GO

CREATE TABLE [game_modes] (
  [id] uuid PRIMARY KEY,
  [code] varchar(30) UNIQUE NOT NULL,
  [name] varchar(100) NOT NULL,
  [team_count] smallint NOT NULL,
  [team_size] smallint NOT NULL,
  [is_ranked] boolean NOT NULL DEFAULT (false),
  [is_active] boolean NOT NULL DEFAULT (true)
)
GO

CREATE TABLE [matchmaking_tickets] (
  [id] uuid PRIMARY KEY,
  [player_id] uuid NOT NULL,
  [party_id] uuid,
  [game_mode_id] uuid NOT NULL,
  [region] varchar(20) NOT NULL,
  [rating_at_queue] integer NOT NULL,
  [latency_ms] jsonb,
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('queued', 'matched', 'cancelled', 'timed_out')) DEFAULT 'queued',
  [created_at] timestamptz NOT NULL DEFAULT (now()),
  [matched_at] timestamptz,
  [match_id] uuid
)
GO

CREATE TABLE [matches] (
  [id] uuid PRIMARY KEY,
  [game_mode_id] uuid NOT NULL,
  [season_id] uuid,
  [region] varchar(20) NOT NULL,
  [server_id] varchar(100),
  [server_build] varchar(40),
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('allocating', 'in_progress', 'completed', 'abandoned', 'invalidated')) DEFAULT 'allocating',
  [started_at] timestamptz,
  [ended_at] timestamptz,
  [winning_team] smallint
)
GO

CREATE TABLE [match_participants] (
  [match_id] uuid NOT NULL,
  [player_id] uuid NOT NULL,
  [team] smallint NOT NULL,
  [party_id] uuid,
  [outcome] nvarchar(255) CHECK ([outcome] IN ('win', 'loss', 'draw', 'abandoned')),
  [placement] smallint,
  [score] integer,
  [stats] jsonb,
  [joined_at] timestamptz NOT NULL,
  [left_at] timestamptz,
  PRIMARY KEY ([match_id], [player_id])
)
GO

CREATE TABLE [rating_events] (
  [id] uuid PRIMARY KEY,
  [player_id] uuid NOT NULL,
  [game_mode_id] uuid NOT NULL,
  [season_id] uuid NOT NULL,
  [match_id] uuid,
  [kind] nvarchar(255) NOT NULL CHECK ([kind] IN ('match', 'season_reset', 'decay', 'correction')),
  [rating_before] integer NOT NULL,
  [rating_after] integer NOT NULL,
  [uncertainty_after] numeric(6,2),
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [player_ratings] (
  [player_id] uuid NOT NULL,
  [game_mode_id] uuid NOT NULL,
  [season_id] uuid NOT NULL,
  [rating] integer NOT NULL,
  [uncertainty] numeric(6,2),
  [games_played] integer NOT NULL DEFAULT (0),
  [wins] integer NOT NULL DEFAULT (0),
  [last_rating_event_id] uuid NOT NULL,
  [updated_at] timestamptz NOT NULL,
  PRIMARY KEY ([player_id], [game_mode_id], [season_id])
)
GO

CREATE TABLE [leaderboard_snapshots] (
  [id] uuid PRIMARY KEY,
  [game_mode_id] uuid NOT NULL,
  [season_id] uuid NOT NULL,
  [region] varchar(20),
  [taken_at] timestamptz NOT NULL,
  [is_final] boolean NOT NULL DEFAULT (false)
)
GO

CREATE TABLE [leaderboard_entries] (
  [snapshot_id] uuid NOT NULL,
  [rank] integer NOT NULL,
  [player_id] uuid NOT NULL,
  [rating] integer NOT NULL,
  [display_name] varchar(40) NOT NULL,
  PRIMARY KEY ([snapshot_id], [rank])
)
GO

CREATE TABLE [achievements] (
  [id] uuid PRIMARY KEY,
  [code] varchar(60) UNIQUE NOT NULL,
  [name] varchar(120) NOT NULL,
  [description] varchar(500) NOT NULL,
  [target_value] integer NOT NULL DEFAULT (1),
  [is_hidden] boolean NOT NULL DEFAULT (false),
  [reward_item_id] uuid,
  [reward_currency_id] uuid,
  [reward_amount] bigint
)
GO

CREATE TABLE [player_achievements] (
  [player_id] uuid NOT NULL,
  [achievement_id] uuid NOT NULL,
  [progress] integer NOT NULL DEFAULT (0),
  [completed_at] timestamptz,
  [reward_claimed_at] timestamptz,
  [updated_at] timestamptz NOT NULL,
  PRIMARY KEY ([player_id], [achievement_id])
)
GO

CREATE TABLE [friendships] (
  [player_low_id] uuid NOT NULL,
  [player_high_id] uuid NOT NULL,
  [requested_by] uuid NOT NULL,
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('pending', 'accepted')) DEFAULT 'pending',
  [created_at] timestamptz NOT NULL DEFAULT (now()),
  [accepted_at] timestamptz,
  PRIMARY KEY ([player_low_id], [player_high_id])
)
GO

CREATE TABLE [parties] (
  [id] uuid PRIMARY KEY,
  [leader_id] uuid NOT NULL,
  [game_mode_id] uuid,
  [max_size] smallint NOT NULL,
  [invite_code] varchar(12) UNIQUE,
  [created_at] timestamptz NOT NULL DEFAULT (now()),
  [disbanded_at] timestamptz
)
GO

CREATE TABLE [party_members] (
  [party_id] uuid NOT NULL,
  [player_id] uuid NOT NULL,
  [joined_at] timestamptz NOT NULL DEFAULT (now()),
  [left_at] timestamptz,
  PRIMARY KEY ([party_id], [player_id])
)
GO

CREATE TABLE [guilds] (
  [id] uuid PRIMARY KEY,
  [name] varchar(50) UNIQUE NOT NULL,
  [tag] varchar(5) UNIQUE NOT NULL,
  [description] varchar(500),
  [member_limit] smallint NOT NULL DEFAULT (50),
  [is_open] boolean NOT NULL DEFAULT (false),
  [created_at] timestamptz NOT NULL DEFAULT (now()),
  [disbanded_at] timestamptz
)
GO

CREATE TABLE [guild_members] (
  [id] uuid PRIMARY KEY,
  [guild_id] uuid NOT NULL,
  [player_id] uuid NOT NULL,
  [role] nvarchar(255) NOT NULL CHECK ([role] IN ('leader', 'officer', 'member', 'recruit')) DEFAULT 'member',
  [joined_at] timestamptz NOT NULL DEFAULT (now()),
  [left_at] timestamptz,
  [left_reason] nvarchar(255) CHECK ([left_reason] IN ('left', 'kicked', 'guild_disbanded'))
)
GO

CREATE TABLE [staff_accounts] (
  [id] uuid PRIMARY KEY,
  [email] varchar(254) UNIQUE NOT NULL,
  [name] varchar(120) NOT NULL,
  [role] nvarchar(255) NOT NULL CHECK ([role] IN ('support', 'moderator', 'live_ops', 'admin')),
  [disabled_at] timestamptz
)
GO

CREATE TABLE [player_reports] (
  [id] uuid PRIMARY KEY,
  [reporter_id] uuid NOT NULL,
  [reported_player_id] uuid NOT NULL,
  [match_id] uuid,
  [reason] nvarchar(255) NOT NULL CHECK ([reason] IN ('cheating', 'griefing', 'abusive_chat', 'offensive_name', 'win_trading', 'account_sharing', 'other')),
  [details] varchar(1000),
  [created_at] timestamptz NOT NULL DEFAULT (now()),
  [reviewed_at] timestamptz,
  [reviewed_by] uuid,
  [sanction_id] uuid
)
GO

CREATE TABLE [sanctions] (
  [id] uuid PRIMARY KEY,
  [player_id] uuid NOT NULL,
  [kind] nvarchar(255) NOT NULL CHECK ([kind] IN ('warning', 'chat_mute', 'matchmaking_cooldown', 'ranked_ban', 'temporary_ban', 'permanent_ban')),
  [reason] nvarchar(255) NOT NULL CHECK ([reason] IN ('cheating', 'griefing', 'abusive_chat', 'offensive_name', 'win_trading', 'account_sharing', 'other')),
  [details] text,
  [issued_by] uuid,
  [evidence_match_id] uuid,
  [starts_at] timestamptz NOT NULL DEFAULT (now()),
  [expires_at] timestamptz,
  [revoked_at] timestamptz,
  [revoked_by] uuid,
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE UNIQUE INDEX [players_index_0] ON [players] ("display_name", "name_tag")
GO

CREATE INDEX [platform_identities_index_1] ON [platform_identities] ("platform_id", "external_user_id")
GO

CREATE INDEX [platform_identities_index_2] ON [platform_identities] ("player_id")
GO

CREATE UNIQUE INDEX [wallet_ledger_entries_index_3] ON [wallet_ledger_entries] ("player_id", "currency_id", "sequence")
GO

CREATE INDEX [inventory_items_index_4] ON [inventory_items] ("player_id", "item_id")
GO

CREATE UNIQUE INDEX [purchases_index_5] ON [purchases] ("platform_id", "platform_transaction_id")
GO

CREATE INDEX [purchases_index_6] ON [purchases] ("player_id", "created_at")
GO

CREATE INDEX [matchmaking_tickets_index_7] ON [matchmaking_tickets] ("game_mode_id", "region", "status", "created_at")
GO

CREATE INDEX [match_participants_index_8] ON [match_participants] ("player_id", "joined_at")
GO

CREATE INDEX [rating_events_index_9] ON [rating_events] ("player_id", "game_mode_id", "season_id", "created_at")
GO

CREATE UNIQUE INDEX [rating_events_index_10] ON [rating_events] ("player_id", "match_id", "kind")
GO

CREATE INDEX [player_ratings_index_11] ON [player_ratings] ("game_mode_id", "season_id", "rating")
GO

CREATE UNIQUE INDEX [leaderboard_entries_index_12] ON [leaderboard_entries] ("snapshot_id", "player_id")
GO

CREATE INDEX [friendships_index_13] ON [friendships] ("player_high_id")
GO

CREATE INDEX [party_members_index_14] ON [party_members] ("player_id")
GO

CREATE INDEX [guild_members_index_15] ON [guild_members] ("player_id")
GO

CREATE INDEX [guild_members_index_16] ON [guild_members] ("guild_id", "role")
GO

CREATE INDEX [player_reports_index_17] ON [player_reports] ("reported_player_id", "created_at")
GO

CREATE INDEX [sanctions_index_18] ON [sanctions] ("player_id", "expires_at")
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Storefronts, console networks and mobile app stores the game ships on. Platforms are data, not schema, so adding one is an INSERT.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'platforms';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Your own short code per integration, e.g. pc_store_a, console_b, mobile_store_a',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'platforms',
@level2type = N'Column', @level2name = 'code';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Whether purchases can arrive with a receipt from this platform',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'platforms',
@level2type = N'Column', @level2name = 'has_store';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'The game account, independent of any platform. Wallet, inventory and ratings hang off this id, which is what makes cross-progression possible.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'players';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Four-digit suffix, so display names need not be unique: "Raven#4821"',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'players',
@level2type = N'Column', @level2name = 'name_tag';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'CACHE of active sanctions, refreshed when one starts, expires or is revoked',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'players',
@level2type = N'Column', @level2name = 'status';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Soft delete for data-deletion requests. Ledger rows stay, keyed by an id that no longer identifies anyone',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'players',
@level2type = N'Column', @level2name = 'deleted_at';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Linked platform accounts. Sign-in looks up (platform, external id) to find the player; a player on three platforms has three rows.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'platform_identities';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'The account id the platform hands over after sign-in',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'platform_identities',
@level2type = N'Column', @level2name = 'external_user_id';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'What other players see: equipped cosmetics, title and level. Split from players so a busy profile never locks the account row.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'player_profiles';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'An equipped cosmetic must be owned: checked against inventory on equip',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'player_profiles',
@level2type = N'Column', @level2name = 'avatar_item_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'A display title unlocked by an achievement',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'player_profiles',
@level2type = N'Column', @level2name = 'title_achievement_id';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Virtual currencies. Premium currency is bought, so it carries refund and chargeback obligations that soft currency does not.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'currencies';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. GOLD (soft), GEMS (premium)',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'currencies',
@level2type = N'Column', @level2name = 'code';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Cap enforced when a credit is written; null for no cap',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'currencies',
@level2type = N'Column', @level2name = 'max_balance';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Only premium currency is sold for real money',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'currencies',
@level2type = N'Column', @level2name = 'is_purchasable';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'The wallet. There is no balance column anywhere to UPDATE: every change to every currency is an insert here, with its cause. A duplication exploit shows up as rows with a reason, and any balance can be recomputed from history.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'wallet_ledger_entries';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Per player and currency: 1, 2, 3 with no gaps',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'wallet_ledger_entries',
@level2type = N'Column', @level2name = 'sequence';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Signed: a credit is positive, a debit negative. Never zero',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'wallet_ledger_entries',
@level2type = N'Column', @level2name = 'amount';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Running balance, computed at insert from the previous row (locked FOR UPDATE). A CHECK keeps it at or above zero',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'wallet_ledger_entries',
@level2type = N'Column', @level2name = 'balance_after';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Required for admin adjustments, so an insider grant is always attributed',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'wallet_ledger_entries',
@level2type = N'Column', @level2name = 'staff_account_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. purchase:<id>:credit or match:<id>:reward. A retried grant collides here instead of paying twice',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'wallet_ledger_entries',
@level2type = N'Column', @level2name = 'idempotency_key';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'The item catalog: everything a player can own.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'items';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Consumables stack into one inventory row with a quantity',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'items',
@level2type = N'Column', @level2name = 'is_stackable';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'No longer obtainable. Owned copies are kept',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'items',
@level2type = N'Column', @level2name = 'retired_at';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Item instances a player owns, each pointing at whatever granted it. Revoking is a timestamp, so support can always answer "where did this come from?"',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'inventory_items';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Remaining uses for stackable consumables; 1 for everything else',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'inventory_items',
@level2type = N'Column', @level2name = 'quantity';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Rentals and time-limited boosts',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'inventory_items',
@level2type = N'Column', @level2name = 'expires_at';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Set by a refund or chargeback. The row stays as evidence',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'inventory_items',
@level2type = N'Column', @level2name = 'revoked_at';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'What the in-game store sells: a bundle of contents for one price, in real money or a virtual currency.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'store_offers';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Set when priced in a virtual currency',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'store_offers',
@level2type = N'Column', @level2name = 'price_currency_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'In units of price_currency_id',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'store_offers',
@level2type = N'Column', @level2name = 'price_amount';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Set when priced in real money: the product id configured in each platform store. Real prices live in the store, not here',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'store_offers',
@level2type = N'Column', @level2name = 'platform_product_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Limited-time offers',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'store_offers',
@level2type = N'Column', @level2name = 'ends_at';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. 1 for a starter pack',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'store_offers',
@level2type = N'Column', @level2name = 'max_per_player';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'What an offer grants. Exactly one of item_id and currency_id per row, so a gem pack is just an offer whose only content is currency.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'offer_contents';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Every purchase, as a state machine: validate the receipt server-side with the platform, then fulfil by writing ledger and inventory rows keyed on this id. Never trust a client that says it paid.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'purchases';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null for purchases paid in virtual currency',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'purchases',
@level2type = N'Column', @level2name = 'platform_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'The receipt or order id issued by the platform store',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'purchases',
@level2type = N'Column', @level2name = 'platform_transaction_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Raw receipt as received, kept for disputes and re-validation',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'purchases',
@level2type = N'Column', @level2name = 'receipt_payload';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Real-money amount as reported by the store',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'purchases',
@level2type = N'Column', @level2name = 'price_cents';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Competitive seasons. Ratings and leaderboards are scoped to one.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'seasons';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'How far ratings are pulled toward the mean at season start',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'seasons',
@level2type = N'Column', @level2name = 'soft_reset_factor';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Playlists. A rating only means something within one mode, so ratings are keyed by it.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'game_modes';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. ranked_5v5, casual_ffa',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'game_modes',
@level2type = N'Column', @level2name = 'code';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'A request to play. Kept after matching, so time-to-match and abandoned queues can be measured.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'matchmaking_tickets';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'The player who queued; for a party, its leader',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'matchmaking_tickets',
@level2type = N'Column', @level2name = 'player_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. eu-west, us-east',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'matchmaking_tickets',
@level2type = N'Column', @level2name = 'region';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Snapshot used for matching; a party queues on a combined rating',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'matchmaking_tickets',
@level2type = N'Column', @level2name = 'rating_at_queue';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Measured ping per region, e.g. {"eu-west": 31, "us-east": 104}',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'matchmaking_tickets',
@level2type = N'Column', @level2name = 'latency_ms';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'One played game, with results written by the authoritative server, never by a client. An invalidated match keeps its row but pays no rewards and moves no ratings.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'matches';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Allocated dedicated server or session host',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'matches',
@level2type = N'Column', @level2name = 'server_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Game server version, for when a bug invalidates every match played on one build',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'matches',
@level2type = N'Column', @level2name = 'server_build';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Who played, on which team, and how it went for them. Rewards and rating changes are computed from these rows.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'match_participants';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Finishing position, for free-for-all modes',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'match_participants',
@level2type = N'Column', @level2name = 'placement';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Mode-specific numbers, e.g. kills, assists, objectives',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'match_participants',
@level2type = N'Column', @level2name = 'stats';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Earlier than the match end means the player left early',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'match_participants',
@level2type = N'Column', @level2name = 'left_at';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Append-only MMR history per player, per mode, per season. Undoing the games lost to a banned cheater is a new correction row, never an edit.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'rating_events';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null for season resets and decay',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'rating_events',
@level2type = N'Column', @level2name = 'match_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Rating deviation, for systems that track confidence as well as skill',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'rating_events',
@level2type = N'Column', @level2name = 'uncertainty_after';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'CACHE of the latest rating_events row, for the matchmaker and the profile. Rebuildable from history at any time.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'player_ratings';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'The event this cache was built from',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'player_ratings',
@level2type = N'Column', @level2name = 'last_rating_event_id';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'A leaderboard frozen at a moment, e.g. every 15 minutes. Readers page through a snapshot instead of sorting a live table, and the final one is the permanent record.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'leaderboard_snapshots';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null for the global board',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'leaderboard_snapshots',
@level2type = N'Column', @level2name = 'region';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'The end-of-season board that season rewards are paid from',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'leaderboard_snapshots',
@level2type = N'Column', @level2name = 'is_final';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'The ranked rows of a snapshot. Usually only the top few thousand are stored.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'leaderboard_entries';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Ties broken by who reached the rating first',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'leaderboard_entries',
@level2type = N'Column', @level2name = 'rank';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Copied at snapshot time, so the board reads without a join and shows the name used then',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'leaderboard_entries',
@level2type = N'Column', @level2name = 'display_name';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Achievement definitions and what they pay out.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'achievements';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. 100 for "win 100 ranked matches"',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'achievements',
@level2type = N'Column', @level2name = 'target_value';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Secret until unlocked',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'achievements',
@level2type = N'Column', @level2name = 'is_hidden';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Progress toward each achievement, created on first progress.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'player_achievements';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Claiming writes the ledger or inventory row; its idempotency key stops a double claim',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'player_achievements',
@level2type = N'Column', @level2name = 'reward_claimed_at';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Mutual friendships stored once, as an ordered pair, so A-B and B-A can never both exist. A friends list reads both columns.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'friendships';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'The smaller of the two ids (CHECK player_low_id < player_high_id)',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'friendships',
@level2type = N'Column', @level2name = 'player_low_id';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'A group that queues together. Short-lived, but kept for match history and for spotting win-trading groups.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'parties';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'What the party is about to queue for',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'parties',
@level2type = N'Column', @level2name = 'game_mode_id';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Who is, or was, in a party.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'party_members';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Long-lived player organizations: guilds, clans, crews.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'guilds';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Short tag shown beside member names, e.g. [ABC]',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'guilds',
@level2type = N'Column', @level2name = 'tag';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Open guilds accept joins without an invite',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'guilds',
@level2type = N'Column', @level2name = 'is_open';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Membership history with roles. Leadership is a role, not a column on guilds, so a handover is two updates in one transaction.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'guild_members';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Support agents, moderators and live-ops staff. Kept apart from players: staff never act through a game account.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'staff_accounts';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'In-game reports. Volume per reported player feeds automated review; one report rarely decides anything alone.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'player_reports';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'The match it happened in, so a reviewer can pull the replay',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'player_reports',
@level2type = N'Column', @level2name = 'match_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'The sanction it led to, if any',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'player_reports',
@level2type = N'Column', @level2name = 'sanction_id';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Warnings, chat mutes, queue cooldowns, ranked bans and account bans, each a row with a time window. A ban is a sanction, so its history and appeal live in one place; players.status only caches what is active.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'sanctions';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null for automated systems such as anti-cheat',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'sanctions',
@level2type = N'Column', @level2name = 'issued_by';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null for permanent',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'sanctions',
@level2type = N'Column', @level2name = 'expires_at';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Overturned on appeal. The row stays',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'sanctions',
@level2type = N'Column', @level2name = 'revoked_at';
GO

ALTER TABLE [platform_identities] ADD FOREIGN KEY ([player_id]) REFERENCES [players] ([id])
GO

ALTER TABLE [platform_identities] ADD FOREIGN KEY ([platform_id]) REFERENCES [platforms] ([id])
GO

ALTER TABLE [player_profiles] ADD FOREIGN KEY ([player_id]) REFERENCES [players] ([id])
GO

ALTER TABLE [player_profiles] ADD FOREIGN KEY ([avatar_item_id]) REFERENCES [items] ([id])
GO

ALTER TABLE [player_profiles] ADD FOREIGN KEY ([banner_item_id]) REFERENCES [items] ([id])
GO

ALTER TABLE [player_profiles] ADD FOREIGN KEY ([title_achievement_id]) REFERENCES [achievements] ([id])
GO

ALTER TABLE [wallet_ledger_entries] ADD FOREIGN KEY ([player_id]) REFERENCES [players] ([id])
GO

ALTER TABLE [wallet_ledger_entries] ADD FOREIGN KEY ([currency_id]) REFERENCES [currencies] ([id])
GO

ALTER TABLE [wallet_ledger_entries] ADD FOREIGN KEY ([purchase_id]) REFERENCES [purchases] ([id])
GO

ALTER TABLE [wallet_ledger_entries] ADD FOREIGN KEY ([match_id]) REFERENCES [matches] ([id])
GO

ALTER TABLE [wallet_ledger_entries] ADD FOREIGN KEY ([achievement_id]) REFERENCES [achievements] ([id])
GO

ALTER TABLE [wallet_ledger_entries] ADD FOREIGN KEY ([staff_account_id]) REFERENCES [staff_accounts] ([id])
GO

ALTER TABLE [inventory_items] ADD FOREIGN KEY ([player_id]) REFERENCES [players] ([id])
GO

ALTER TABLE [inventory_items] ADD FOREIGN KEY ([item_id]) REFERENCES [items] ([id])
GO

ALTER TABLE [inventory_items] ADD FOREIGN KEY ([purchase_id]) REFERENCES [purchases] ([id])
GO

ALTER TABLE [inventory_items] ADD FOREIGN KEY ([match_id]) REFERENCES [matches] ([id])
GO

ALTER TABLE [inventory_items] ADD FOREIGN KEY ([achievement_id]) REFERENCES [achievements] ([id])
GO

ALTER TABLE [store_offers] ADD FOREIGN KEY ([price_currency_id]) REFERENCES [currencies] ([id])
GO

ALTER TABLE [offer_contents] ADD FOREIGN KEY ([store_offer_id]) REFERENCES [store_offers] ([id])
GO

ALTER TABLE [offer_contents] ADD FOREIGN KEY ([item_id]) REFERENCES [items] ([id])
GO

ALTER TABLE [offer_contents] ADD FOREIGN KEY ([currency_id]) REFERENCES [currencies] ([id])
GO

ALTER TABLE [purchases] ADD FOREIGN KEY ([player_id]) REFERENCES [players] ([id])
GO

ALTER TABLE [purchases] ADD FOREIGN KEY ([store_offer_id]) REFERENCES [store_offers] ([id])
GO

ALTER TABLE [purchases] ADD FOREIGN KEY ([platform_id]) REFERENCES [platforms] ([id])
GO

ALTER TABLE [matchmaking_tickets] ADD FOREIGN KEY ([player_id]) REFERENCES [players] ([id])
GO

ALTER TABLE [matchmaking_tickets] ADD FOREIGN KEY ([party_id]) REFERENCES [parties] ([id])
GO

ALTER TABLE [matchmaking_tickets] ADD FOREIGN KEY ([game_mode_id]) REFERENCES [game_modes] ([id])
GO

ALTER TABLE [matchmaking_tickets] ADD FOREIGN KEY ([match_id]) REFERENCES [matches] ([id])
GO

ALTER TABLE [matches] ADD FOREIGN KEY ([game_mode_id]) REFERENCES [game_modes] ([id])
GO

ALTER TABLE [matches] ADD FOREIGN KEY ([season_id]) REFERENCES [seasons] ([id])
GO

ALTER TABLE [match_participants] ADD FOREIGN KEY ([match_id]) REFERENCES [matches] ([id])
GO

ALTER TABLE [match_participants] ADD FOREIGN KEY ([player_id]) REFERENCES [players] ([id])
GO

ALTER TABLE [match_participants] ADD FOREIGN KEY ([party_id]) REFERENCES [parties] ([id])
GO

ALTER TABLE [rating_events] ADD FOREIGN KEY ([player_id]) REFERENCES [players] ([id])
GO

ALTER TABLE [rating_events] ADD FOREIGN KEY ([game_mode_id]) REFERENCES [game_modes] ([id])
GO

ALTER TABLE [rating_events] ADD FOREIGN KEY ([season_id]) REFERENCES [seasons] ([id])
GO

ALTER TABLE [rating_events] ADD FOREIGN KEY ([match_id]) REFERENCES [matches] ([id])
GO

ALTER TABLE [player_ratings] ADD FOREIGN KEY ([player_id]) REFERENCES [players] ([id])
GO

ALTER TABLE [player_ratings] ADD FOREIGN KEY ([game_mode_id]) REFERENCES [game_modes] ([id])
GO

ALTER TABLE [player_ratings] ADD FOREIGN KEY ([season_id]) REFERENCES [seasons] ([id])
GO

ALTER TABLE [player_ratings] ADD FOREIGN KEY ([last_rating_event_id]) REFERENCES [rating_events] ([id])
GO

ALTER TABLE [leaderboard_snapshots] ADD FOREIGN KEY ([game_mode_id]) REFERENCES [game_modes] ([id])
GO

ALTER TABLE [leaderboard_snapshots] ADD FOREIGN KEY ([season_id]) REFERENCES [seasons] ([id])
GO

ALTER TABLE [leaderboard_entries] ADD FOREIGN KEY ([snapshot_id]) REFERENCES [leaderboard_snapshots] ([id])
GO

ALTER TABLE [leaderboard_entries] ADD FOREIGN KEY ([player_id]) REFERENCES [players] ([id])
GO

ALTER TABLE [achievements] ADD FOREIGN KEY ([reward_item_id]) REFERENCES [items] ([id])
GO

ALTER TABLE [achievements] ADD FOREIGN KEY ([reward_currency_id]) REFERENCES [currencies] ([id])
GO

ALTER TABLE [player_achievements] ADD FOREIGN KEY ([player_id]) REFERENCES [players] ([id])
GO

ALTER TABLE [player_achievements] ADD FOREIGN KEY ([achievement_id]) REFERENCES [achievements] ([id])
GO

ALTER TABLE [friendships] ADD FOREIGN KEY ([player_low_id]) REFERENCES [players] ([id])
GO

ALTER TABLE [friendships] ADD FOREIGN KEY ([player_high_id]) REFERENCES [players] ([id])
GO

ALTER TABLE [friendships] ADD FOREIGN KEY ([requested_by]) REFERENCES [players] ([id])
GO

ALTER TABLE [parties] ADD FOREIGN KEY ([leader_id]) REFERENCES [players] ([id])
GO

ALTER TABLE [parties] ADD FOREIGN KEY ([game_mode_id]) REFERENCES [game_modes] ([id])
GO

ALTER TABLE [party_members] ADD FOREIGN KEY ([party_id]) REFERENCES [parties] ([id])
GO

ALTER TABLE [party_members] ADD FOREIGN KEY ([player_id]) REFERENCES [players] ([id])
GO

ALTER TABLE [guild_members] ADD FOREIGN KEY ([guild_id]) REFERENCES [guilds] ([id])
GO

ALTER TABLE [guild_members] ADD FOREIGN KEY ([player_id]) REFERENCES [players] ([id])
GO

ALTER TABLE [player_reports] ADD FOREIGN KEY ([reporter_id]) REFERENCES [players] ([id])
GO

ALTER TABLE [player_reports] ADD FOREIGN KEY ([reported_player_id]) REFERENCES [players] ([id])
GO

ALTER TABLE [player_reports] ADD FOREIGN KEY ([match_id]) REFERENCES [matches] ([id])
GO

ALTER TABLE [player_reports] ADD FOREIGN KEY ([reviewed_by]) REFERENCES [staff_accounts] ([id])
GO

ALTER TABLE [player_reports] ADD FOREIGN KEY ([sanction_id]) REFERENCES [sanctions] ([id])
GO

ALTER TABLE [sanctions] ADD FOREIGN KEY ([player_id]) REFERENCES [players] ([id])
GO

ALTER TABLE [sanctions] ADD FOREIGN KEY ([issued_by]) REFERENCES [staff_accounts] ([id])
GO

ALTER TABLE [sanctions] ADD FOREIGN KEY ([evidence_match_id]) REFERENCES [matches] ([id])
GO

ALTER TABLE [sanctions] ADD FOREIGN KEY ([revoked_by]) REFERENCES [staff_accounts] ([id])
GO

How to use this template

  1. Open the ER diagram to see the tables and how they relate.
  2. Copy it into your workspace. You get your own editable copy, in DBML.
  3. Export it as PostgreSQL, MySQL, or SQL Server DDL, or as Prisma, Drizzle, SQLAlchemy, TypeScript, Zod or C# models.

The copy opens in DB Planner’s ER diagram tool, with the schema as text in the DBML editor beside it. Have a database already? Turn its SQL into an ER diagram instead.

Frequently asked questions

Which table is at the centre of the Multiplayer Game Backend database schema?
players. It is referenced by 16 other tables: friendships, guild_members, inventory_items, leaderboard_entries, match_participants and 11 more.
How is friendships related to players?
friendships.player_high_id references players.id, a many to one relationship. All 67 relationships in the schema are listed on this page.
Which table in the Multiplayer Game Backend database schema has the most columns?
purchases, with 13 columns, followed by wallet_ledger_entries (13) and sanctions (12). The schema has 245 columns across 30 tables.
Can I export it to PostgreSQL or MySQL?
Yes. Every DB Planner template exports as DBML, as PostgreSQL, MySQL, or SQL Server DDL, and as C# models.
Is this template free?
Yes. You can open it in the browser without an account, and copy it into your own workspace with a free DB Planner account.
Can I change it after copying it?
Yes. A copy is yours: you can rename tables, add columns, and export it. Changes the author makes later do not affect your copy.