Music Streaming ER diagram and database schema

The Music Streaming database schema is a DB Planner template with 26 tables, 177 columns and 40 relationships, free to use. Core tables include artists, audio_files, availability_windows, devices. It can be opened as an interactive ER diagram or exported as PostgreSQL, MySQL, or SQL Server DDL.

ER diagram of the Music Streaming database schema, showing 26 tables and their relationships
FIG. 1: entity relationship diagram, 26 tables
Tables
26
Columns
177
Relationships
40
Category
Social
Exports
DBML, SQL, Prisma, C#
Price
Free

What this schema models

A complete music streaming app database design, modeled on how streaming services actually separate catalog, rights and listening: 26 tables, 11 enums and 40 relationships covering artists, releases, tracks, credits and genres, labels, territory availability windows and audio encodings, users, plans, per-country prices and family subscriptions, playlists, collaborators, follows and saved library items, devices and the play event stream, and daily play counts feeding pro-rata royalty pools and statements. THE FOUR DESIGN RULES 1. A RELEASE is not a TRACK. A track is a recording with an ISRC; a release (album, single, EP or compilation) has a UPC and a tracklist with disc and position. The same song on the single and on the album is one track, with one play count and one royalty line. 2. Credits are rows with roles. Many artists link to a track as main, featured, producer, writer, composer or remixer, in display order. "A feat. B" is rendered from those rows, never stored as a string, so the featured artist page finds the track too. 3. Play events are an append-only firehose; reports read rollups. play_events is partitioned monthly by played_at, never updated, and copies the territory and plan tier at play time. A daily job rolls it up into play_counts per track, territory and tier, which charts, artist dashboards and royalty runs read instead. 4. Royalties are pooled, then split by share of streams. Each month the net revenue of a territory and tier forms a pool; the per-stream rate is revenue times the rights share divided by qualified streams (30 seconds or more), and each label statement is its qualified streams times that rate. DETAILS WORTH STEALING - Playlists order tracks by a lexicographic rank, so dragging track 900 to the top of a 1,000-track playlist rewrites one row; entries have their own id because a track can appear twice. - Follows and library saves use one nullable foreign key per target plus a check constraint, so every follow is an enforced foreign key instead of a generic target_id. - Availability windows are per release, territory and access tier, and a takedown ends a window instead of deleting the release, so play history survives. - Audio files are one row per encoding, with codec, bitrate, loudness for volume normalization and a preview flag; a CDN serves the bytes. - Duo and family plans have members, with a partial unique index allowing one current plan per user; prices are per country and versioned, and a subscription keeps the price it was sold at. - unique_listeners in the daily rollup is flagged as not summable across days, a classic bug in monthly listener reports. WHAT YOU GET Clean DBML that imports directly into DB Planner, and a laid-out board with zones color-coded and framed: listening, users and subscriptions, library and social, catalog, rights and media, and play counts and royalties. Every table carries a note. Postgres-flavoured types that port cleanly to MySQL or SQL Server. Useful for developers building a music or audio streaming app, and for students who need a realistic music streaming ER diagram for a DBMS project. This is a schema design reference; real royalty deals, publishing rights and licensing terms vary widely and belong in your own business logic.

Tables (26)

Every table and its columns

artists

Performers, bands, producers and writers: anyone who can be credited on a track or a release.

Columns of the artists table
ColumnTypeConstraintsReferencesDescription
iduuidPK
namevarchar(200)not null
sort_namevarchar(200)not nullFor A to Z browsing, e.g. "Midnight Owls, The"
slugvarchar(200)unique, not null
biotext
countrychar(2)
image_keyvarchar(300)Object storage key
is_verifiedbooleannot null, default false
monthly_listenersintegerCache, recomputed daily over a trailing 28 days
created_attimestamptznot null, default `now()`

genres

A genre tree. Browsing a parent includes its children.

Columns of the genres table
ColumnTypeConstraintsReferencesDescription
iduuidPK
namevarchar(100)unique, not null
parent_iduuidFKgenres.ide.g. Deep house under House under Electronic

releases

An album, single, EP or compilation: the product people browse and save. It has a tracklist; it holds no audio itself.

Columns of the releases table
ColumnTypeConstraintsReferencesDescription
iduuidPK
titlevarchar(300)not null
kindrelease_kindnot null
label_iduuidFKlabels.idNull for a self-released record
upcvarchar(14)uniqueUniversal Product Code, the identifier distributors and stores use for a release
release_datedatenot null
original_release_datedateSet for a remaster or reissue
cover_art_keyvarchar(300)
explicitbooleannot null, default false
copyright_linevarchar(300)The P line, e.g. "(P) 2024 Example Records"
statusrelease_statusnot null, default 'draft'
created_attimestamptznot null, default `now()`

release_artists

Headline artists of a release, which can differ from the track credits; a compilation has none and shows as Various Artists.

Columns of the release_artists table
ColumnTypeConstraintsReferencesDescription
release_iduuidFK, not nullreleases.id
artist_iduuidFK, not nullartists.id
positionsmallintnot null, default 1Display order of the headline artists

tracks

A recording. The same song on the single and on the album is ONE track, with one play count and one royalty line.

Columns of the tracks table
ColumnTypeConstraintsReferencesDescription
iduuidPK
titlevarchar(300)not null
versionvarchar(100)e.g. Radio edit, Live, 2011 Remaster
isrcchar(12)uniqueInternational Standard Recording Code: one per recording, the key royalty reports are matched on
duration_msintegernot null
explicitbooleannot null, default false
label_iduuidFKlabels.idOwner of the sound recording, which can differ from the label of a compilation it appears on
created_attimestamptznot null, default `now()`

release_tracks

The tracklist: which recordings appear on a release, on which disc, in which position.

Columns of the release_tracks table
ColumnTypeConstraintsReferences
release_iduuidFK, not nullreleases.id
track_iduuidFK, not nulltracks.id
disc_numbersmallintnot null, default 1
track_numbersmallintnot null

Indexes: (release_id, disc_number, track_number) unique

track_credits

Many artists per track, each with a role. The display string "A feat. B" is rendered from these rows, never stored, so a featured artist page finds the track too.

Columns of the track_credits table
ColumnTypeConstraintsReferencesDescription
track_iduuidFK, not nulltracks.id
artist_iduuidFK, not nullartists.id
rolecredit_rolenot null
positionsmallintnot null, default 1Order within the role, so "A, B feat. C" renders in the right order

Indexes: (artist_id, role)

track_genres

Genres per track. A release shows the genres of its tracks.

Columns of the track_genres table
ColumnTypeConstraintsReferences
track_iduuidFK, not nulltracks.id
genre_iduuidFK, not nullgenres.id

labels

Rights holders for the sound recordings: labels, their imprints, and distributors acting for independent artists. Royalty statements are issued to them.

Columns of the labels table
ColumnTypeConstraintsReferencesDescription
iduuidPK
namevarchar(200)not null
parent_label_iduuidFKlabels.idFor an imprint of a larger label group
is_distributorbooleannot null, default falseDistributes on behalf of independent artists
payout_account_tokenvarchar(200)Bank account held by the payment processor

availability_windows

Where and when a release may be streamed under its license. A track plays only if a window for one of its releases covers the listener territory, plan and the current time.

Columns of the availability_windows table
ColumnTypeConstraintsReferencesDescription
iduuidPK
release_iduuidFK, not nullreleases.id
territorychar(2)not nullISO 3166-1 alpha-2 country code
accesstier_accessnot nullpremium_only for a release windowed away from free listeners
starts_attimestamptznot null
ends_attimestamptzNull for open-ended. Set it to take a release down without deleting anything.

Indexes: (release_id, territory, starts_at) unique

audio_files

One encoding of a track. The player picks a file by plan quality and network conditions.

Columns of the audio_files table
ColumnTypeConstraintsReferencesDescription
iduuidPK
track_iduuidFK, not nulltracks.id
codecaudio_codecnot null
bitrate_kbpssmallintnot nullNominal bitrate; the average for lossless
sample_rate_hzintegernot null
bit_depthsmallintLossless only, e.g. 16 or 24
storage_keyvarchar(300)not nullObject storage key. A CDN serves the file, never the database.
size_bytesbigintnot null
loudness_lufsnumeric(5,2)Integrated loudness, for volume normalization between tracks
is_previewbooleannot null, default false30-second clip for listeners without access

Indexes: (track_id, codec, bitrate_kbps, is_preview) unique

users

Listeners. A user is on the free tier unless a live subscription says otherwise.

Columns of the users table
ColumnTypeConstraintsReferencesDescription
iduuidPK
emailvarchar(254)unique, not null
display_namevarchar(100)not null
handlevarchar(30)unique
countrychar(2)not nullLicensing territory, set from billing or location and not freely editable
birth_datedateFor explicit content defaults on minor accounts
explicit_filterbooleannot null, default false
created_attimestamptznot null, default `now()`

subscription_plans

What can be bought. Prices live per territory in plan_prices.

Columns of the subscription_plans table
ColumnTypeConstraintsReferencesDescription
iduuidPK
codevarchar(30)unique, not nulle.g. individual, duo, family, student
namevarchar(100)not null
tierplan_tiernot null
max_memberssmallintnot null, default 1Seats on the plan, e.g. 6 for a family plan
max_bitrate_kbpssmallintnot null
offline_downloadsbooleannot null, default false

plan_prices

Plan prices per country, versioned. A subscription keeps the price it was sold at until it is deliberately moved to a new one.

Columns of the plan_prices table
ColumnTypeConstraintsReferences
iduuidPK
subscription_plan_iduuidFK, not nullsubscription_plans.id
territorychar(2)not null
currencychar(3)not null
monthly_price_centsintegernot null
valid_fromdatenot null
valid_todate

Indexes: (subscription_plan_id, territory, valid_from) unique

subscriptions

A paid plan. Its revenue feeds the royalty pool for its territory and tier.

Columns of the subscriptions table
ColumnTypeConstraintsReferencesDescription
iduuidPK
owner_user_iduuidFK, not nullusers.idThe payer
subscription_plan_iduuidFK, not nullsubscription_plans.id
plan_price_iduuidFK, not nullplan_prices.idThe price this subscription is billed at
statussubscription_statusnot null
started_attimestamptznot null
current_period_endtimestamptznot null
cancel_at_period_endbooleannot null, default false
cancelled_attimestamptz
processor_referencevarchar(100)uniqueRecurring billing is delegated to the payment processor

Indexes: (owner_user_id)

subscription_members

Who shares a duo or family plan, owner included. Premium access for each member comes from this row, so leaving the plan drops that member to free.

Columns of the subscription_members table
ColumnTypeConstraintsReferences
subscription_iduuidFK, not nullsubscriptions.id
user_iduuidFK, not nullusers.id
joined_attimestamptznot null
left_attimestamptz

Indexes: (user_id)

playlists

User and editorial playlists.

Columns of the playlists table
ColumnTypeConstraintsReferencesDescription
iduuidPK
owner_user_iduuidFKusers.idNull for an editorial playlist owned by the service
titlevarchar(200)not null
descriptionvarchar(1000)
is_publicbooleannot null, default true
is_collaborativebooleannot null, default false
cover_image_keyvarchar(300)
follower_countintegernot null, default 0Cache of follows
created_attimestamptznot null, default `now()`
updated_attimestamptznot null, default `now()`

playlist_tracks

The ordered entries of a playlist. Dragging track 900 to the top of a 1,000-track playlist updates one row, not a thousand position numbers.

Columns of the playlist_tracks table
ColumnTypeConstraintsReferencesDescription
iduuidPKOwn id, because the same track can appear twice in one playlist
playlist_iduuidFK, not nullplaylists.id
track_iduuidFK, not nulltracks.id
rankvarchar(64)not nullLexicographic sort key. A move writes one new key that sorts between the new neighbours.
added_byuuidFKusers.idWho added it, which matters on a collaborative playlist
added_attimestamptznot null, default `now()`

Indexes: (playlist_id, rank) unique

playlist_collaborators

Who besides the owner may edit a collaborative playlist.

Columns of the playlist_collaborators table
ColumnTypeConstraintsReferences
playlist_iduuidFK, not nullplaylists.id
user_iduuidFK, not nullusers.id
invited_attimestamptznot null, default `now()`

follows

Users following users, artists or playlists. One nullable foreign key per target, with a check constraint that exactly one is set, instead of a generic target_id: every follow is a real, enforced foreign key.

Columns of the follows table
ColumnTypeConstraintsReferences
iduuidPK
follower_iduuidFK, not nullusers.id
followed_user_iduuidFKusers.id
followed_artist_iduuidFKartists.id
followed_playlist_iduuidFKplaylists.id
created_attimestamptznot null, default `now()`

Indexes: (follower_id, followed_user_id) unique, (follower_id, followed_artist_id) unique, (follower_id, followed_playlist_id) unique, (followed_artist_id)

library_saves

Liked songs and saved albums, with the same exactly-one-target pattern as follows. Saving an album does not save each of its tracks.

Columns of the library_saves table
ColumnTypeConstraintsReferences
iduuidPK
user_iduuidFK, not nullusers.id
track_iduuidFKtracks.id
release_iduuidFKreleases.id
saved_attimestamptznot null, default `now()`

Indexes: (user_id, track_id) unique, (user_id, release_id) unique, (user_id, saved_at)

devices

Where a user listens. Concurrent stream limits and offline download limits are enforced per device.

Columns of the devices table
ColumnTypeConstraintsReferencesDescription
iduuidPK
user_iduuidFK, not nullusers.id
kinddevice_kindnot null
namevarchar(100)e.g. Kitchen speaker
app_versionvarchar(30)
last_seen_attimestamptz

play_events

Append-only: one row each time playback stops, from every listener, and larger than every other table combined. Partition by played_at (monthly), write in batches from the event pipeline, never update a row, and detach old partitions to cold storage. Territory and plan tier are copied onto the event so royalties never depend on what the user looks like today. Reports read play_counts, never this table.

Columns of the play_events table
ColumnTypeConstraintsReferencesDescription
user_iduuidFK, not nullusers.id
played_attimestamptznot nullWhen playback started; device time for offline plays
track_iduuidFK, not nulltracks.id
device_iduuidFKdevices.id
ms_playedintegernot null
is_qualifiedbooleannot nullPlayed at least 30 seconds, the usual threshold for a stream to count toward royalties
end_reasonplay_end_reasonnot null
context_kindplay_contextnot null
context_iduuidThe playlist, release or artist it was played from, per context_kind
territorychar(2)not nullCopied from the user at play time
plan_tierplan_tiernot nullCopied at play time: free and premium streams are paid from different pools
offlinebooleannot null, default falsePlayed offline and uploaded on the next sync

Indexes: (track_id, played_at)

play_counts

Daily rollup of play_events per track, territory and tier, rebuilt idempotently for a whole day by a batch job. Charts, artist dashboards and royalty runs read this table.

Columns of the play_counts table
ColumnTypeConstraintsReferencesDescription
track_iduuidFK, not nulltracks.id
period_datedatenot nullOne row per day; months are sums of days
territorychar(2)not null
plan_tierplan_tiernot null
streamsintegernot nullEvery play, however short
qualified_streamsintegernot nullPlays of 30 seconds or more; royalties are paid on these
unique_listenersintegernot nullDoes NOT sum across days; monthly listeners need their own rollup

Indexes: (period_date, territory, plan_tier)

royalty_pools

The pro-rata royalty model: each month the revenue of a territory and tier is pooled, and the per-stream rate is net revenue times rights share divided by total qualified streams.

Columns of the royalty_pools table
ColumnTypeConstraintsReferencesDescription
iduuidPK
period_monthdatenot nullFirst day of the month
territorychar(2)not null
plan_tierplan_tiernot null
currencychar(3)not null
net_revenue_centsbigintnot nullSubscription or ad revenue for the territory and tier, after tax
rights_share_bpsintegernot nullShare of revenue paid out to rights holders
total_qualified_streamsbigintnot null
statusroyalty_statusnot null, default 'draft'
computed_attimestamptz

Indexes: (period_month, territory, plan_tier) unique

royalty_statements

What each rights holder is owed from one pool. A statement is issued once its pool is final and never edited after payment; a correction goes on a later statement.

Columns of the royalty_statements table
ColumnTypeConstraintsReferencesDescription
iduuidPK
royalty_pool_iduuidFK, not nullroyalty_pools.id
label_iduuidFK, not nulllabels.id
qualified_streamsbigintnot nullSum of play_counts for tracks this label owns, in the pool
amount_centsbigintnot nullqualified_streams times the pool rate
currencychar(3)not null
issued_attimestamptz
paid_attimestamptz
processor_referencevarchar(100)unique

Indexes: (royalty_pool_id, label_id) unique

Enums (11)

release_kind
album, single, ep, compilation
release_status
draft, scheduled, live, taken_down
credit_role
main, featured, producer, writer, composer, remixer
tier_access
all_listeners, premium_only
audio_codec
aac, ogg_vorbis, mp3, flac
plan_tier
free, premium
subscription_status
trialing, active, past_due, cancelled, expired
device_kind
phone, tablet, desktop, web, speaker, car, tv
play_context
release, playlist, artist, radio, search, library
play_end_reason
finished, skipped, stopped, error
royalty_status
draft, final, paid

Relationships (40)

  • audio_files.track_id references tracks.id many to one
  • availability_windows.release_id references releases.id many to one
  • devices.user_id references users.id many to one
  • follows.followed_artist_id references artists.id many to one
  • follows.followed_playlist_id references playlists.id many to one
  • follows.followed_user_id references users.id many to one
  • follows.follower_id references users.id many to one
  • genres.parent_id references genres.id many to one
  • labels.parent_label_id references labels.id many to one
  • library_saves.release_id references releases.id many to one
  • library_saves.track_id references tracks.id many to one
  • library_saves.user_id references users.id many to one
  • plan_prices.subscription_plan_id references subscription_plans.id many to one
  • play_counts.track_id references tracks.id many to one
  • play_events.device_id references devices.id many to one
  • play_events.track_id references tracks.id many to one
  • play_events.user_id references users.id many to one
  • playlist_collaborators.playlist_id references playlists.id many to one
  • playlist_collaborators.user_id references users.id many to one
  • playlist_tracks.added_by references users.id many to one
  • playlist_tracks.playlist_id references playlists.id many to one
  • playlist_tracks.track_id references tracks.id many to one
  • playlists.owner_user_id references users.id many to one
  • release_artists.artist_id references artists.id many to one
  • release_artists.release_id references releases.id many to one
  • release_tracks.release_id references releases.id many to one
  • release_tracks.track_id references tracks.id many to one
  • releases.label_id references labels.id many to one
  • royalty_statements.label_id references labels.id many to one
  • royalty_statements.royalty_pool_id references royalty_pools.id many to one
  • subscription_members.subscription_id references subscriptions.id many to one
  • subscription_members.user_id references users.id many to one
  • subscriptions.owner_user_id references users.id many to one
  • subscriptions.plan_price_id references plan_prices.id many to one
  • subscriptions.subscription_plan_id references subscription_plans.id many to one
  • track_credits.artist_id references artists.id many to one
  • track_credits.track_id references tracks.id many to one
  • track_genres.genre_id references genres.id many to one
  • track_genres.track_id references tracks.id many to one
  • tracks.label_id references labels.id many to one

Music Streaming 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.

music-streaming.dbml dbml
// Music Streaming
// Zones (header colors): catalog (blue), rights and media (teal),
// users and subscriptions (green), library and social (amber),
// listening (coral), play counts and royalties (purple).

// ---------------------------------------------------------------------------
// CATALOG: recordings, the releases they appear on, and who made them
// ---------------------------------------------------------------------------

Table artists [headercolor: #4c8bf5] {
  id uuid [pk]
  name varchar(200) [not null]
  sort_name varchar(200) [not null, note: 'For A to Z browsing, e.g. "Midnight Owls, The"']
  slug varchar(200) [not null, unique]
  bio text
  country char(2)
  image_key varchar(300) [note: 'Object storage key']
  is_verified boolean [not null, default: false]
  monthly_listeners integer [note: 'Cache, recomputed daily over a trailing 28 days']
  created_at timestamptz [not null, default: `now()`]
  Note: 'Performers, bands, producers and writers: anyone who can be credited on a track or a release.'
}

Table genres [headercolor: #4c8bf5] {
  id uuid [pk]
  name varchar(100) [not null, unique]
  parent_id uuid [ref: > genres.id, note: 'e.g. Deep house under House under Electronic']
  Note: 'A genre tree. Browsing a parent includes its children.'
}

Table releases [headercolor: #4c8bf5] {
  id uuid [pk]
  title varchar(300) [not null]
  kind release_kind [not null]
  label_id uuid [ref: > labels.id, note: 'Null for a self-released record']
  upc varchar(14) [unique, note: 'Universal Product Code, the identifier distributors and stores use for a release']
  release_date date [not null]
  original_release_date date [note: 'Set for a remaster or reissue']
  cover_art_key varchar(300)
  explicit boolean [not null, default: false]
  copyright_line varchar(300) [note: 'The P line, e.g. "(P) 2024 Example Records"']
  status release_status [not null, default: 'draft']
  created_at timestamptz [not null, default: `now()`]
  Note: 'An album, single, EP or compilation: the product people browse and save. It has a tracklist; it holds no audio itself.'
}

Table release_artists [headercolor: #4c8bf5] {
  release_id uuid [not null, ref: > releases.id]
  artist_id uuid [not null, ref: > artists.id]
  position smallint [not null, default: 1, note: 'Display order of the headline artists']

  indexes {
    (release_id, artist_id) [pk]
  }

  Note: 'Headline artists of a release, which can differ from the track credits; a compilation has none and shows as Various Artists.'
}

Table tracks [headercolor: #4c8bf5] {
  id uuid [pk]
  title varchar(300) [not null]
  version varchar(100) [note: 'e.g. Radio edit, Live, 2011 Remaster']
  isrc char(12) [unique, note: 'International Standard Recording Code: one per recording, the key royalty reports are matched on']
  duration_ms integer [not null]
  explicit boolean [not null, default: false]
  label_id uuid [ref: > labels.id, note: 'Owner of the sound recording, which can differ from the label of a compilation it appears on']
  created_at timestamptz [not null, default: `now()`]
  Note: 'A recording. The same song on the single and on the album is ONE track, with one play count and one royalty line.'
}

Table release_tracks [headercolor: #4c8bf5] {
  release_id uuid [not null, ref: > releases.id]
  track_id uuid [not null, ref: > tracks.id]
  disc_number smallint [not null, default: 1]
  track_number smallint [not null]

  indexes {
    (release_id, track_id) [pk]
    (release_id, disc_number, track_number) [unique]
  }

  Note: 'The tracklist: which recordings appear on a release, on which disc, in which position.'
}

Table track_credits [headercolor: #4c8bf5] {
  track_id uuid [not null, ref: > tracks.id]
  artist_id uuid [not null, ref: > artists.id]
  role credit_role [not null]
  position smallint [not null, default: 1, note: 'Order within the role, so "A, B feat. C" renders in the right order']

  indexes {
    (track_id, artist_id, role) [pk]
    (artist_id, role) [note: 'An artist page: everything they appear on, by role']
  }

  Note: 'Many artists per track, each with a role. The display string "A feat. B" is rendered from these rows, never stored, so a featured artist page finds the track too.'
}

Table track_genres [headercolor: #4c8bf5] {
  track_id uuid [not null, ref: > tracks.id]
  genre_id uuid [not null, ref: > genres.id]

  indexes {
    (track_id, genre_id) [pk]
  }

  Note: 'Genres per track. A release shows the genres of its tracks.'
}

// ---------------------------------------------------------------------------
// RIGHTS AND MEDIA: who owns it, where it may play, and the files
// ---------------------------------------------------------------------------

Table labels [headercolor: #4cd0b0] {
  id uuid [pk]
  name varchar(200) [not null]
  parent_label_id uuid [ref: > labels.id, note: 'For an imprint of a larger label group']
  is_distributor boolean [not null, default: false, note: 'Distributes on behalf of independent artists']
  payout_account_token varchar(200) [note: 'Bank account held by the payment processor']
  Note: 'Rights holders for the sound recordings: labels, their imprints, and distributors acting for independent artists. Royalty statements are issued to them.'
}

Table availability_windows [headercolor: #4cd0b0] {
  id uuid [pk]
  release_id uuid [not null, ref: > releases.id]
  territory char(2) [not null, note: 'ISO 3166-1 alpha-2 country code']
  access tier_access [not null, note: 'premium_only for a release windowed away from free listeners']
  starts_at timestamptz [not null]
  ends_at timestamptz [note: 'Null for open-ended. Set it to take a release down without deleting anything.']

  indexes {
    (release_id, territory, starts_at) [unique]
  }

  Note: 'Where and when a release may be streamed under its license. A track plays only if a window for one of its releases covers the listener territory, plan and the current time.'
}

Table audio_files [headercolor: #4cd0b0] {
  id uuid [pk]
  track_id uuid [not null, ref: > tracks.id]
  codec audio_codec [not null]
  bitrate_kbps smallint [not null, note: 'Nominal bitrate; the average for lossless']
  sample_rate_hz integer [not null]
  bit_depth smallint [note: 'Lossless only, e.g. 16 or 24']
  storage_key varchar(300) [not null, note: 'Object storage key. A CDN serves the file, never the database.']
  size_bytes bigint [not null]
  loudness_lufs numeric(5,2) [note: 'Integrated loudness, for volume normalization between tracks']
  is_preview boolean [not null, default: false, note: '30-second clip for listeners without access']

  indexes {
    (track_id, codec, bitrate_kbps, is_preview) [unique]
  }

  Note: 'One encoding of a track. The player picks a file by plan quality and network conditions.'
}

// ---------------------------------------------------------------------------
// USERS AND SUBSCRIPTIONS
// ---------------------------------------------------------------------------

Table users [headercolor: #8bc34a] {
  id uuid [pk]
  email varchar(254) [not null, unique]
  display_name varchar(100) [not null]
  handle varchar(30) [unique]
  country char(2) [not null, note: 'Licensing territory, set from billing or location and not freely editable']
  birth_date date [note: 'For explicit content defaults on minor accounts']
  explicit_filter boolean [not null, default: false]
  created_at timestamptz [not null, default: `now()`]
  Note: 'Listeners. A user is on the free tier unless a live subscription says otherwise.'
}

Table subscription_plans [headercolor: #8bc34a] {
  id uuid [pk]
  code varchar(30) [not null, unique, note: 'e.g. individual, duo, family, student']
  name varchar(100) [not null]
  tier plan_tier [not null]
  max_members smallint [not null, default: 1, note: 'Seats on the plan, e.g. 6 for a family plan']
  max_bitrate_kbps smallint [not null]
  offline_downloads boolean [not null, default: false]
  Note: 'What can be bought. Prices live per territory in plan_prices.'
}

Table plan_prices [headercolor: #8bc34a] {
  id uuid [pk]
  subscription_plan_id uuid [not null, ref: > subscription_plans.id]
  territory char(2) [not null]
  currency char(3) [not null]
  monthly_price_cents integer [not null]
  valid_from date [not null]
  valid_to date

  indexes {
    (subscription_plan_id, territory, valid_from) [unique]
  }

  Note: 'Plan prices per country, versioned. A subscription keeps the price it was sold at until it is deliberately moved to a new one.'
}

Table subscriptions [headercolor: #8bc34a] {
  id uuid [pk]
  owner_user_id uuid [not null, ref: > users.id, note: 'The payer']
  subscription_plan_id uuid [not null, ref: > subscription_plans.id]
  plan_price_id uuid [not null, ref: > plan_prices.id, note: 'The price this subscription is billed at']
  status subscription_status [not null]
  started_at timestamptz [not null]
  current_period_end timestamptz [not null]
  cancel_at_period_end boolean [not null, default: false]
  cancelled_at timestamptz
  processor_reference varchar(100) [unique, note: 'Recurring billing is delegated to the payment processor']

  indexes {
    owner_user_id [name: 'one_live_subscription', note: 'Partial unique index WHERE status IN (trialing, active, past_due)']
  }

  Note: 'A paid plan. Its revenue feeds the royalty pool for its territory and tier.'
}

Table subscription_members [headercolor: #8bc34a] {
  subscription_id uuid [not null, ref: > subscriptions.id]
  user_id uuid [not null, ref: > users.id]
  joined_at timestamptz [not null]
  left_at timestamptz

  indexes {
    (subscription_id, user_id) [pk]
    user_id [name: 'one_current_plan', note: 'Partial unique index WHERE left_at IS NULL: one plan per user at a time']
  }

  Note: 'Who shares a duo or family plan, owner included. Premium access for each member comes from this row, so leaving the plan drops that member to free.'
}

// ---------------------------------------------------------------------------
// LIBRARY AND SOCIAL: playlists, saves and follows
// ---------------------------------------------------------------------------

Table playlists [headercolor: #f5b74c] {
  id uuid [pk]
  owner_user_id uuid [ref: > users.id, note: 'Null for an editorial playlist owned by the service']
  title varchar(200) [not null]
  description varchar(1000)
  is_public boolean [not null, default: true]
  is_collaborative boolean [not null, default: false]
  cover_image_key varchar(300)
  follower_count integer [not null, default: 0, note: 'Cache of follows']
  created_at timestamptz [not null, default: `now()`]
  updated_at timestamptz [not null, default: `now()`]
  Note: 'User and editorial playlists.'
}

Table playlist_tracks [headercolor: #f5b74c] {
  id uuid [pk, note: 'Own id, because the same track can appear twice in one playlist']
  playlist_id uuid [not null, ref: > playlists.id]
  track_id uuid [not null, ref: > tracks.id]
  rank varchar(64) [not null, note: 'Lexicographic sort key. A move writes one new key that sorts between the new neighbours.']
  added_by uuid [ref: > users.id, note: 'Who added it, which matters on a collaborative playlist']
  added_at timestamptz [not null, default: `now()`]

  indexes {
    (playlist_id, rank) [unique]
  }

  Note: 'The ordered entries of a playlist. Dragging track 900 to the top of a 1,000-track playlist updates one row, not a thousand position numbers.'
}

Table playlist_collaborators [headercolor: #f5b74c] {
  playlist_id uuid [not null, ref: > playlists.id]
  user_id uuid [not null, ref: > users.id]
  invited_at timestamptz [not null, default: `now()`]

  indexes {
    (playlist_id, user_id) [pk]
  }

  Note: 'Who besides the owner may edit a collaborative playlist.'
}

Table follows [headercolor: #f5b74c] {
  id uuid [pk]
  follower_id uuid [not null, ref: > users.id]
  followed_user_id uuid [ref: > users.id]
  followed_artist_id uuid [ref: > artists.id]
  followed_playlist_id uuid [ref: > playlists.id]
  created_at timestamptz [not null, default: `now()`]

  indexes {
    (follower_id, followed_user_id) [unique]
    (follower_id, followed_artist_id) [unique]
    (follower_id, followed_playlist_id) [unique]
    followed_artist_id [note: 'Followers of an artist, for new release notifications']
  }

  Note: 'Users following users, artists or playlists. One nullable foreign key per target, with a check constraint that exactly one is set, instead of a generic target_id: every follow is a real, enforced foreign key.'
}

Table library_saves [headercolor: #f5b74c] {
  id uuid [pk]
  user_id uuid [not null, ref: > users.id]
  track_id uuid [ref: > tracks.id]
  release_id uuid [ref: > releases.id]
  saved_at timestamptz [not null, default: `now()`]

  indexes {
    (user_id, track_id) [unique]
    (user_id, release_id) [unique]
    (user_id, saved_at) [note: 'The library, most recent first']
  }

  Note: 'Liked songs and saved albums, with the same exactly-one-target pattern as follows. Saving an album does not save each of its tracks.'
}

// ---------------------------------------------------------------------------
// LISTENING: the append-only firehose
// ---------------------------------------------------------------------------

Table devices [headercolor: #f07178] {
  id uuid [pk]
  user_id uuid [not null, ref: > users.id]
  kind device_kind [not null]
  name varchar(100) [note: 'e.g. Kitchen speaker']
  app_version varchar(30)
  last_seen_at timestamptz
  Note: 'Where a user listens. Concurrent stream limits and offline download limits are enforced per device.'
}

Table play_events [headercolor: #f07178] {
  user_id uuid [not null, ref: > users.id]
  played_at timestamptz [not null, note: 'When playback started; device time for offline plays']
  track_id uuid [not null, ref: > tracks.id]
  device_id uuid [ref: > devices.id]
  ms_played integer [not null]
  is_qualified boolean [not null, note: 'Played at least 30 seconds, the usual threshold for a stream to count toward royalties']
  end_reason play_end_reason [not null]
  context_kind play_context [not null]
  context_id uuid [note: 'The playlist, release or artist it was played from, per context_kind']
  territory char(2) [not null, note: 'Copied from the user at play time']
  plan_tier plan_tier [not null, note: 'Copied at play time: free and premium streams are paid from different pools']
  offline boolean [not null, default: false, note: 'Played offline and uploaded on the next sync']

  indexes {
    (user_id, played_at, track_id) [pk, note: 'Includes played_at because a partitioned table needs the partition key in its primary key']
    (track_id, played_at)
  }

  Note: '''Append-only: one row each time playback stops, from every listener, and larger than every other table combined.
Partition by played_at (monthly), write in batches from the event pipeline, never update a row, and detach old partitions to cold storage.
Territory and plan tier are copied onto the event so royalties never depend on what the user looks like today. Reports read play_counts, never this table.'''
}

// ---------------------------------------------------------------------------
// PLAY COUNTS AND ROYALTIES: rolled up, then paid out
// ---------------------------------------------------------------------------

Table play_counts [headercolor: #b98cf0] {
  track_id uuid [not null, ref: > tracks.id]
  period_date date [not null, note: 'One row per day; months are sums of days']
  territory char(2) [not null]
  plan_tier plan_tier [not null]
  streams integer [not null, note: 'Every play, however short']
  qualified_streams integer [not null, note: 'Plays of 30 seconds or more; royalties are paid on these']
  unique_listeners integer [not null, note: 'Does NOT sum across days; monthly listeners need their own rollup']

  indexes {
    (track_id, period_date, territory, plan_tier) [pk]
    (period_date, territory, plan_tier) [note: 'A royalty run reads one month, territory and tier at a time']
  }

  Note: 'Daily rollup of play_events per track, territory and tier, rebuilt idempotently for a whole day by a batch job. Charts, artist dashboards and royalty runs read this table.'
}

Table royalty_pools [headercolor: #b98cf0] {
  id uuid [pk]
  period_month date [not null, note: 'First day of the month']
  territory char(2) [not null]
  plan_tier plan_tier [not null]
  currency char(3) [not null]
  net_revenue_cents bigint [not null, note: 'Subscription or ad revenue for the territory and tier, after tax']
  rights_share_bps integer [not null, note: 'Share of revenue paid out to rights holders']
  total_qualified_streams bigint [not null]
  status royalty_status [not null, default: 'draft']
  computed_at timestamptz

  indexes {
    (period_month, territory, plan_tier) [unique]
  }

  Note: 'The pro-rata royalty model: each month the revenue of a territory and tier is pooled, and the per-stream rate is net revenue times rights share divided by total qualified streams.'
}

Table royalty_statements [headercolor: #b98cf0] {
  id uuid [pk]
  royalty_pool_id uuid [not null, ref: > royalty_pools.id]
  label_id uuid [not null, ref: > labels.id]
  qualified_streams bigint [not null, note: 'Sum of play_counts for tracks this label owns, in the pool']
  amount_cents bigint [not null, note: 'qualified_streams times the pool rate']
  currency char(3) [not null]
  issued_at timestamptz
  paid_at timestamptz
  processor_reference varchar(100) [unique]

  indexes {
    (royalty_pool_id, label_id) [unique]
  }

  Note: 'What each rights holder is owed from one pool. A statement is issued once its pool is final and never edited after payment; a correction goes on a later statement.'
}

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

Enum release_kind {
  album
  single
  ep
  compilation
}

Enum release_status {
  draft
  scheduled
  live
  taken_down
}

Enum credit_role {
  main
  featured
  producer
  writer
  composer
  remixer
}

Enum tier_access {
  all_listeners
  premium_only
}

Enum audio_codec {
  aac
  ogg_vorbis
  mp3
  flac
}

Enum plan_tier {
  free
  premium
}

Enum subscription_status {
  trialing
  active
  past_due
  cancelled
  expired
}

Enum device_kind {
  phone
  tablet
  desktop
  web
  speaker
  car
  tv
}

Enum play_context {
  release
  playlist
  artist
  radio
  search
  library
}

Enum play_end_reason {
  finished
  skipped
  stopped
  error
}

Enum royalty_status {
  draft
  final
  paid
}

Music Streaming 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 "release_kind" AS ENUM (
  'album',
  'single',
  'ep',
  'compilation'
);

CREATE TYPE "release_status" AS ENUM (
  'draft',
  'scheduled',
  'live',
  'taken_down'
);

CREATE TYPE "credit_role" AS ENUM (
  'main',
  'featured',
  'producer',
  'writer',
  'composer',
  'remixer'
);

CREATE TYPE "tier_access" AS ENUM (
  'all_listeners',
  'premium_only'
);

CREATE TYPE "audio_codec" AS ENUM (
  'aac',
  'ogg_vorbis',
  'mp3',
  'flac'
);

CREATE TYPE "plan_tier" AS ENUM (
  'free',
  'premium'
);

CREATE TYPE "subscription_status" AS ENUM (
  'trialing',
  'active',
  'past_due',
  'cancelled',
  'expired'
);

CREATE TYPE "device_kind" AS ENUM (
  'phone',
  'tablet',
  'desktop',
  'web',
  'speaker',
  'car',
  'tv'
);

CREATE TYPE "play_context" AS ENUM (
  'release',
  'playlist',
  'artist',
  'radio',
  'search',
  'library'
);

CREATE TYPE "play_end_reason" AS ENUM (
  'finished',
  'skipped',
  'stopped',
  'error'
);

CREATE TYPE "royalty_status" AS ENUM (
  'draft',
  'final',
  'paid'
);

CREATE TABLE "artists" (
  "id" uuid PRIMARY KEY,
  "name" varchar(200) NOT NULL,
  "sort_name" varchar(200) NOT NULL,
  "slug" varchar(200) UNIQUE NOT NULL,
  "bio" text,
  "country" char(2),
  "image_key" varchar(300),
  "is_verified" boolean NOT NULL DEFAULT false,
  "monthly_listeners" integer,
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "genres" (
  "id" uuid PRIMARY KEY,
  "name" varchar(100) UNIQUE NOT NULL,
  "parent_id" uuid
);

CREATE TABLE "releases" (
  "id" uuid PRIMARY KEY,
  "title" varchar(300) NOT NULL,
  "kind" release_kind NOT NULL,
  "label_id" uuid,
  "upc" varchar(14) UNIQUE,
  "release_date" date NOT NULL,
  "original_release_date" date,
  "cover_art_key" varchar(300),
  "explicit" boolean NOT NULL DEFAULT false,
  "copyright_line" varchar(300),
  "status" release_status NOT NULL DEFAULT 'draft',
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "release_artists" (
  "release_id" uuid NOT NULL,
  "artist_id" uuid NOT NULL,
  "position" smallint NOT NULL DEFAULT 1,
  PRIMARY KEY ("release_id", "artist_id")
);

CREATE TABLE "tracks" (
  "id" uuid PRIMARY KEY,
  "title" varchar(300) NOT NULL,
  "version" varchar(100),
  "isrc" char(12) UNIQUE,
  "duration_ms" integer NOT NULL,
  "explicit" boolean NOT NULL DEFAULT false,
  "label_id" uuid,
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "release_tracks" (
  "release_id" uuid NOT NULL,
  "track_id" uuid NOT NULL,
  "disc_number" smallint NOT NULL DEFAULT 1,
  "track_number" smallint NOT NULL,
  PRIMARY KEY ("release_id", "track_id")
);

CREATE TABLE "track_credits" (
  "track_id" uuid NOT NULL,
  "artist_id" uuid NOT NULL,
  "role" credit_role NOT NULL,
  "position" smallint NOT NULL DEFAULT 1,
  PRIMARY KEY ("track_id", "artist_id", "role")
);

CREATE TABLE "track_genres" (
  "track_id" uuid NOT NULL,
  "genre_id" uuid NOT NULL,
  PRIMARY KEY ("track_id", "genre_id")
);

CREATE TABLE "labels" (
  "id" uuid PRIMARY KEY,
  "name" varchar(200) NOT NULL,
  "parent_label_id" uuid,
  "is_distributor" boolean NOT NULL DEFAULT false,
  "payout_account_token" varchar(200)
);

CREATE TABLE "availability_windows" (
  "id" uuid PRIMARY KEY,
  "release_id" uuid NOT NULL,
  "territory" char(2) NOT NULL,
  "access" tier_access NOT NULL,
  "starts_at" timestamptz NOT NULL,
  "ends_at" timestamptz
);

CREATE TABLE "audio_files" (
  "id" uuid PRIMARY KEY,
  "track_id" uuid NOT NULL,
  "codec" audio_codec NOT NULL,
  "bitrate_kbps" smallint NOT NULL,
  "sample_rate_hz" integer NOT NULL,
  "bit_depth" smallint,
  "storage_key" varchar(300) NOT NULL,
  "size_bytes" bigint NOT NULL,
  "loudness_lufs" numeric(5,2),
  "is_preview" boolean NOT NULL DEFAULT false
);

CREATE TABLE "users" (
  "id" uuid PRIMARY KEY,
  "email" varchar(254) UNIQUE NOT NULL,
  "display_name" varchar(100) NOT NULL,
  "handle" varchar(30) UNIQUE,
  "country" char(2) NOT NULL,
  "birth_date" date,
  "explicit_filter" boolean NOT NULL DEFAULT false,
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "subscription_plans" (
  "id" uuid PRIMARY KEY,
  "code" varchar(30) UNIQUE NOT NULL,
  "name" varchar(100) NOT NULL,
  "tier" plan_tier NOT NULL,
  "max_members" smallint NOT NULL DEFAULT 1,
  "max_bitrate_kbps" smallint NOT NULL,
  "offline_downloads" boolean NOT NULL DEFAULT false
);

CREATE TABLE "plan_prices" (
  "id" uuid PRIMARY KEY,
  "subscription_plan_id" uuid NOT NULL,
  "territory" char(2) NOT NULL,
  "currency" char(3) NOT NULL,
  "monthly_price_cents" integer NOT NULL,
  "valid_from" date NOT NULL,
  "valid_to" date
);

CREATE TABLE "subscriptions" (
  "id" uuid PRIMARY KEY,
  "owner_user_id" uuid NOT NULL,
  "subscription_plan_id" uuid NOT NULL,
  "plan_price_id" uuid NOT NULL,
  "status" subscription_status NOT NULL,
  "started_at" timestamptz NOT NULL,
  "current_period_end" timestamptz NOT NULL,
  "cancel_at_period_end" boolean NOT NULL DEFAULT false,
  "cancelled_at" timestamptz,
  "processor_reference" varchar(100) UNIQUE
);

CREATE TABLE "subscription_members" (
  "subscription_id" uuid NOT NULL,
  "user_id" uuid NOT NULL,
  "joined_at" timestamptz NOT NULL,
  "left_at" timestamptz,
  PRIMARY KEY ("subscription_id", "user_id")
);

CREATE TABLE "playlists" (
  "id" uuid PRIMARY KEY,
  "owner_user_id" uuid,
  "title" varchar(200) NOT NULL,
  "description" varchar(1000),
  "is_public" boolean NOT NULL DEFAULT true,
  "is_collaborative" boolean NOT NULL DEFAULT false,
  "cover_image_key" varchar(300),
  "follower_count" integer NOT NULL DEFAULT 0,
  "created_at" timestamptz NOT NULL DEFAULT (now()),
  "updated_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "playlist_tracks" (
  "id" uuid PRIMARY KEY,
  "playlist_id" uuid NOT NULL,
  "track_id" uuid NOT NULL,
  "rank" varchar(64) NOT NULL,
  "added_by" uuid,
  "added_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "playlist_collaborators" (
  "playlist_id" uuid NOT NULL,
  "user_id" uuid NOT NULL,
  "invited_at" timestamptz NOT NULL DEFAULT (now()),
  PRIMARY KEY ("playlist_id", "user_id")
);

CREATE TABLE "follows" (
  "id" uuid PRIMARY KEY,
  "follower_id" uuid NOT NULL,
  "followed_user_id" uuid,
  "followed_artist_id" uuid,
  "followed_playlist_id" uuid,
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "library_saves" (
  "id" uuid PRIMARY KEY,
  "user_id" uuid NOT NULL,
  "track_id" uuid,
  "release_id" uuid,
  "saved_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "devices" (
  "id" uuid PRIMARY KEY,
  "user_id" uuid NOT NULL,
  "kind" device_kind NOT NULL,
  "name" varchar(100),
  "app_version" varchar(30),
  "last_seen_at" timestamptz
);

CREATE TABLE "play_events" (
  "user_id" uuid NOT NULL,
  "played_at" timestamptz NOT NULL,
  "track_id" uuid NOT NULL,
  "device_id" uuid,
  "ms_played" integer NOT NULL,
  "is_qualified" boolean NOT NULL,
  "end_reason" play_end_reason NOT NULL,
  "context_kind" play_context NOT NULL,
  "context_id" uuid,
  "territory" char(2) NOT NULL,
  "plan_tier" plan_tier NOT NULL,
  "offline" boolean NOT NULL DEFAULT false,
  PRIMARY KEY ("user_id", "played_at", "track_id")
);

CREATE TABLE "play_counts" (
  "track_id" uuid NOT NULL,
  "period_date" date NOT NULL,
  "territory" char(2) NOT NULL,
  "plan_tier" plan_tier NOT NULL,
  "streams" integer NOT NULL,
  "qualified_streams" integer NOT NULL,
  "unique_listeners" integer NOT NULL,
  PRIMARY KEY ("track_id", "period_date", "territory", "plan_tier")
);

CREATE TABLE "royalty_pools" (
  "id" uuid PRIMARY KEY,
  "period_month" date NOT NULL,
  "territory" char(2) NOT NULL,
  "plan_tier" plan_tier NOT NULL,
  "currency" char(3) NOT NULL,
  "net_revenue_cents" bigint NOT NULL,
  "rights_share_bps" integer NOT NULL,
  "total_qualified_streams" bigint NOT NULL,
  "status" royalty_status NOT NULL DEFAULT 'draft',
  "computed_at" timestamptz
);

CREATE TABLE "royalty_statements" (
  "id" uuid PRIMARY KEY,
  "royalty_pool_id" uuid NOT NULL,
  "label_id" uuid NOT NULL,
  "qualified_streams" bigint NOT NULL,
  "amount_cents" bigint NOT NULL,
  "currency" char(3) NOT NULL,
  "issued_at" timestamptz,
  "paid_at" timestamptz,
  "processor_reference" varchar(100) UNIQUE
);

CREATE UNIQUE INDEX ON "release_tracks" ("release_id", "disc_number", "track_number");

CREATE INDEX ON "track_credits" ("artist_id", "role");

CREATE UNIQUE INDEX ON "availability_windows" ("release_id", "territory", "starts_at");

CREATE UNIQUE INDEX ON "audio_files" ("track_id", "codec", "bitrate_kbps", "is_preview");

CREATE UNIQUE INDEX ON "plan_prices" ("subscription_plan_id", "territory", "valid_from");

CREATE INDEX "one_live_subscription" ON "subscriptions" ("owner_user_id");

CREATE INDEX "one_current_plan" ON "subscription_members" ("user_id");

CREATE UNIQUE INDEX ON "playlist_tracks" ("playlist_id", "rank");

CREATE UNIQUE INDEX ON "follows" ("follower_id", "followed_user_id");

CREATE UNIQUE INDEX ON "follows" ("follower_id", "followed_artist_id");

CREATE UNIQUE INDEX ON "follows" ("follower_id", "followed_playlist_id");

CREATE INDEX ON "follows" ("followed_artist_id");

CREATE UNIQUE INDEX ON "library_saves" ("user_id", "track_id");

CREATE UNIQUE INDEX ON "library_saves" ("user_id", "release_id");

CREATE INDEX ON "library_saves" ("user_id", "saved_at");

CREATE INDEX ON "play_events" ("track_id", "played_at");

CREATE INDEX ON "play_counts" ("period_date", "territory", "plan_tier");

CREATE UNIQUE INDEX ON "royalty_pools" ("period_month", "territory", "plan_tier");

CREATE UNIQUE INDEX ON "royalty_statements" ("royalty_pool_id", "label_id");

COMMENT ON TABLE "artists" IS 'Performers, bands, producers and writers: anyone who can be credited on a track or a release.';

COMMENT ON COLUMN "artists"."sort_name" IS 'For A to Z browsing, e.g. "Midnight Owls, The"';

COMMENT ON COLUMN "artists"."image_key" IS 'Object storage key';

COMMENT ON COLUMN "artists"."monthly_listeners" IS 'Cache, recomputed daily over a trailing 28 days';

COMMENT ON TABLE "genres" IS 'A genre tree. Browsing a parent includes its children.';

COMMENT ON COLUMN "genres"."parent_id" IS 'e.g. Deep house under House under Electronic';

COMMENT ON TABLE "releases" IS 'An album, single, EP or compilation: the product people browse and save. It has a tracklist; it holds no audio itself.';

COMMENT ON COLUMN "releases"."label_id" IS 'Null for a self-released record';

COMMENT ON COLUMN "releases"."upc" IS 'Universal Product Code, the identifier distributors and stores use for a release';

COMMENT ON COLUMN "releases"."original_release_date" IS 'Set for a remaster or reissue';

COMMENT ON COLUMN "releases"."copyright_line" IS 'The P line, e.g. "(P) 2024 Example Records"';

COMMENT ON TABLE "release_artists" IS 'Headline artists of a release, which can differ from the track credits; a compilation has none and shows as Various Artists.';

COMMENT ON COLUMN "release_artists"."position" IS 'Display order of the headline artists';

COMMENT ON TABLE "tracks" IS 'A recording. The same song on the single and on the album is ONE track, with one play count and one royalty line.';

COMMENT ON COLUMN "tracks"."version" IS 'e.g. Radio edit, Live, 2011 Remaster';

COMMENT ON COLUMN "tracks"."isrc" IS 'International Standard Recording Code: one per recording, the key royalty reports are matched on';

COMMENT ON COLUMN "tracks"."label_id" IS 'Owner of the sound recording, which can differ from the label of a compilation it appears on';

COMMENT ON TABLE "release_tracks" IS 'The tracklist: which recordings appear on a release, on which disc, in which position.';

COMMENT ON TABLE "track_credits" IS 'Many artists per track, each with a role. The display string "A feat. B" is rendered from these rows, never stored, so a featured artist page finds the track too.';

COMMENT ON COLUMN "track_credits"."position" IS 'Order within the role, so "A, B feat. C" renders in the right order';

COMMENT ON TABLE "track_genres" IS 'Genres per track. A release shows the genres of its tracks.';

COMMENT ON TABLE "labels" IS 'Rights holders for the sound recordings: labels, their imprints, and distributors acting for independent artists. Royalty statements are issued to them.';

COMMENT ON COLUMN "labels"."parent_label_id" IS 'For an imprint of a larger label group';

COMMENT ON COLUMN "labels"."is_distributor" IS 'Distributes on behalf of independent artists';

COMMENT ON COLUMN "labels"."payout_account_token" IS 'Bank account held by the payment processor';

COMMENT ON TABLE "availability_windows" IS 'Where and when a release may be streamed under its license. A track plays only if a window for one of its releases covers the listener territory, plan and the current time.';

COMMENT ON COLUMN "availability_windows"."territory" IS 'ISO 3166-1 alpha-2 country code';

COMMENT ON COLUMN "availability_windows"."access" IS 'premium_only for a release windowed away from free listeners';

COMMENT ON COLUMN "availability_windows"."ends_at" IS 'Null for open-ended. Set it to take a release down without deleting anything.';

COMMENT ON TABLE "audio_files" IS 'One encoding of a track. The player picks a file by plan quality and network conditions.';

COMMENT ON COLUMN "audio_files"."bitrate_kbps" IS 'Nominal bitrate; the average for lossless';

COMMENT ON COLUMN "audio_files"."bit_depth" IS 'Lossless only, e.g. 16 or 24';

COMMENT ON COLUMN "audio_files"."storage_key" IS 'Object storage key. A CDN serves the file, never the database.';

COMMENT ON COLUMN "audio_files"."loudness_lufs" IS 'Integrated loudness, for volume normalization between tracks';

COMMENT ON COLUMN "audio_files"."is_preview" IS '30-second clip for listeners without access';

COMMENT ON TABLE "users" IS 'Listeners. A user is on the free tier unless a live subscription says otherwise.';

COMMENT ON COLUMN "users"."country" IS 'Licensing territory, set from billing or location and not freely editable';

COMMENT ON COLUMN "users"."birth_date" IS 'For explicit content defaults on minor accounts';

COMMENT ON TABLE "subscription_plans" IS 'What can be bought. Prices live per territory in plan_prices.';

COMMENT ON COLUMN "subscription_plans"."code" IS 'e.g. individual, duo, family, student';

COMMENT ON COLUMN "subscription_plans"."max_members" IS 'Seats on the plan, e.g. 6 for a family plan';

COMMENT ON TABLE "plan_prices" IS 'Plan prices per country, versioned. A subscription keeps the price it was sold at until it is deliberately moved to a new one.';

COMMENT ON TABLE "subscriptions" IS 'A paid plan. Its revenue feeds the royalty pool for its territory and tier.';

COMMENT ON COLUMN "subscriptions"."owner_user_id" IS 'The payer';

COMMENT ON COLUMN "subscriptions"."plan_price_id" IS 'The price this subscription is billed at';

COMMENT ON COLUMN "subscriptions"."processor_reference" IS 'Recurring billing is delegated to the payment processor';

COMMENT ON TABLE "subscription_members" IS 'Who shares a duo or family plan, owner included. Premium access for each member comes from this row, so leaving the plan drops that member to free.';

COMMENT ON TABLE "playlists" IS 'User and editorial playlists.';

COMMENT ON COLUMN "playlists"."owner_user_id" IS 'Null for an editorial playlist owned by the service';

COMMENT ON COLUMN "playlists"."follower_count" IS 'Cache of follows';

COMMENT ON TABLE "playlist_tracks" IS 'The ordered entries of a playlist. Dragging track 900 to the top of a 1,000-track playlist updates one row, not a thousand position numbers.';

COMMENT ON COLUMN "playlist_tracks"."id" IS 'Own id, because the same track can appear twice in one playlist';

COMMENT ON COLUMN "playlist_tracks"."rank" IS 'Lexicographic sort key. A move writes one new key that sorts between the new neighbours.';

COMMENT ON COLUMN "playlist_tracks"."added_by" IS 'Who added it, which matters on a collaborative playlist';

COMMENT ON TABLE "playlist_collaborators" IS 'Who besides the owner may edit a collaborative playlist.';

COMMENT ON TABLE "follows" IS 'Users following users, artists or playlists. One nullable foreign key per target, with a check constraint that exactly one is set, instead of a generic target_id: every follow is a real, enforced foreign key.';

COMMENT ON TABLE "library_saves" IS 'Liked songs and saved albums, with the same exactly-one-target pattern as follows. Saving an album does not save each of its tracks.';

COMMENT ON TABLE "devices" IS 'Where a user listens. Concurrent stream limits and offline download limits are enforced per device.';

COMMENT ON COLUMN "devices"."name" IS 'e.g. Kitchen speaker';

COMMENT ON TABLE "play_events" IS 'Append-only: one row each time playback stops, from every listener, and larger than every other table combined.
Partition by played_at (monthly), write in batches from the event pipeline, never update a row, and detach old partitions to cold storage.
Territory and plan tier are copied onto the event so royalties never depend on what the user looks like today. Reports read play_counts, never this table.';

COMMENT ON COLUMN "play_events"."played_at" IS 'When playback started; device time for offline plays';

COMMENT ON COLUMN "play_events"."is_qualified" IS 'Played at least 30 seconds, the usual threshold for a stream to count toward royalties';

COMMENT ON COLUMN "play_events"."context_id" IS 'The playlist, release or artist it was played from, per context_kind';

COMMENT ON COLUMN "play_events"."territory" IS 'Copied from the user at play time';

COMMENT ON COLUMN "play_events"."plan_tier" IS 'Copied at play time: free and premium streams are paid from different pools';

COMMENT ON COLUMN "play_events"."offline" IS 'Played offline and uploaded on the next sync';

COMMENT ON TABLE "play_counts" IS 'Daily rollup of play_events per track, territory and tier, rebuilt idempotently for a whole day by a batch job. Charts, artist dashboards and royalty runs read this table.';

COMMENT ON COLUMN "play_counts"."period_date" IS 'One row per day; months are sums of days';

COMMENT ON COLUMN "play_counts"."streams" IS 'Every play, however short';

COMMENT ON COLUMN "play_counts"."qualified_streams" IS 'Plays of 30 seconds or more; royalties are paid on these';

COMMENT ON COLUMN "play_counts"."unique_listeners" IS 'Does NOT sum across days; monthly listeners need their own rollup';

COMMENT ON TABLE "royalty_pools" IS 'The pro-rata royalty model: each month the revenue of a territory and tier is pooled, and the per-stream rate is net revenue times rights share divided by total qualified streams.';

COMMENT ON COLUMN "royalty_pools"."period_month" IS 'First day of the month';

COMMENT ON COLUMN "royalty_pools"."net_revenue_cents" IS 'Subscription or ad revenue for the territory and tier, after tax';

COMMENT ON COLUMN "royalty_pools"."rights_share_bps" IS 'Share of revenue paid out to rights holders';

COMMENT ON TABLE "royalty_statements" IS 'What each rights holder is owed from one pool. A statement is issued once its pool is final and never edited after payment; a correction goes on a later statement.';

COMMENT ON COLUMN "royalty_statements"."qualified_streams" IS 'Sum of play_counts for tracks this label owns, in the pool';

COMMENT ON COLUMN "royalty_statements"."amount_cents" IS 'qualified_streams times the pool rate';

ALTER TABLE "genres" ADD FOREIGN KEY ("parent_id") REFERENCES "genres" ("id");

ALTER TABLE "releases" ADD FOREIGN KEY ("label_id") REFERENCES "labels" ("id");

ALTER TABLE "release_artists" ADD FOREIGN KEY ("release_id") REFERENCES "releases" ("id");

ALTER TABLE "release_artists" ADD FOREIGN KEY ("artist_id") REFERENCES "artists" ("id");

ALTER TABLE "tracks" ADD FOREIGN KEY ("label_id") REFERENCES "labels" ("id");

ALTER TABLE "release_tracks" ADD FOREIGN KEY ("release_id") REFERENCES "releases" ("id");

ALTER TABLE "release_tracks" ADD FOREIGN KEY ("track_id") REFERENCES "tracks" ("id");

ALTER TABLE "track_credits" ADD FOREIGN KEY ("track_id") REFERENCES "tracks" ("id");

ALTER TABLE "track_credits" ADD FOREIGN KEY ("artist_id") REFERENCES "artists" ("id");

ALTER TABLE "track_genres" ADD FOREIGN KEY ("track_id") REFERENCES "tracks" ("id");

ALTER TABLE "track_genres" ADD FOREIGN KEY ("genre_id") REFERENCES "genres" ("id");

ALTER TABLE "labels" ADD FOREIGN KEY ("parent_label_id") REFERENCES "labels" ("id");

ALTER TABLE "availability_windows" ADD FOREIGN KEY ("release_id") REFERENCES "releases" ("id");

ALTER TABLE "audio_files" ADD FOREIGN KEY ("track_id") REFERENCES "tracks" ("id");

ALTER TABLE "plan_prices" ADD FOREIGN KEY ("subscription_plan_id") REFERENCES "subscription_plans" ("id");

ALTER TABLE "subscriptions" ADD FOREIGN KEY ("owner_user_id") REFERENCES "users" ("id");

ALTER TABLE "subscriptions" ADD FOREIGN KEY ("subscription_plan_id") REFERENCES "subscription_plans" ("id");

ALTER TABLE "subscriptions" ADD FOREIGN KEY ("plan_price_id") REFERENCES "plan_prices" ("id");

ALTER TABLE "subscription_members" ADD FOREIGN KEY ("subscription_id") REFERENCES "subscriptions" ("id");

ALTER TABLE "subscription_members" ADD FOREIGN KEY ("user_id") REFERENCES "users" ("id");

ALTER TABLE "playlists" ADD FOREIGN KEY ("owner_user_id") REFERENCES "users" ("id");

ALTER TABLE "playlist_tracks" ADD FOREIGN KEY ("playlist_id") REFERENCES "playlists" ("id");

ALTER TABLE "playlist_tracks" ADD FOREIGN KEY ("track_id") REFERENCES "tracks" ("id");

ALTER TABLE "playlist_tracks" ADD FOREIGN KEY ("added_by") REFERENCES "users" ("id");

ALTER TABLE "playlist_collaborators" ADD FOREIGN KEY ("playlist_id") REFERENCES "playlists" ("id");

ALTER TABLE "playlist_collaborators" ADD FOREIGN KEY ("user_id") REFERENCES "users" ("id");

ALTER TABLE "follows" ADD FOREIGN KEY ("follower_id") REFERENCES "users" ("id");

ALTER TABLE "follows" ADD FOREIGN KEY ("followed_user_id") REFERENCES "users" ("id");

ALTER TABLE "follows" ADD FOREIGN KEY ("followed_artist_id") REFERENCES "artists" ("id");

ALTER TABLE "follows" ADD FOREIGN KEY ("followed_playlist_id") REFERENCES "playlists" ("id");

ALTER TABLE "library_saves" ADD FOREIGN KEY ("user_id") REFERENCES "users" ("id");

ALTER TABLE "library_saves" ADD FOREIGN KEY ("track_id") REFERENCES "tracks" ("id");

ALTER TABLE "library_saves" ADD FOREIGN KEY ("release_id") REFERENCES "releases" ("id");

ALTER TABLE "devices" ADD FOREIGN KEY ("user_id") REFERENCES "users" ("id");

ALTER TABLE "play_events" ADD FOREIGN KEY ("user_id") REFERENCES "users" ("id");

ALTER TABLE "play_events" ADD FOREIGN KEY ("track_id") REFERENCES "tracks" ("id");

ALTER TABLE "play_events" ADD FOREIGN KEY ("device_id") REFERENCES "devices" ("id");

ALTER TABLE "play_counts" ADD FOREIGN KEY ("track_id") REFERENCES "tracks" ("id");

ALTER TABLE "royalty_statements" ADD FOREIGN KEY ("royalty_pool_id") REFERENCES "royalty_pools" ("id");

ALTER TABLE "royalty_statements" ADD FOREIGN KEY ("label_id") REFERENCES "labels" ("id");
MySQL
mysql.sql MySQL
CREATE TABLE `artists` (
  `id` uuid PRIMARY KEY,
  `name` varchar(200) NOT NULL,
  `sort_name` varchar(200) NOT NULL COMMENT 'For A to Z browsing, e.g. "Midnight Owls, The"',
  `slug` varchar(200) UNIQUE NOT NULL,
  `bio` text,
  `country` char(2),
  `image_key` varchar(300) COMMENT 'Object storage key',
  `is_verified` boolean NOT NULL DEFAULT false,
  `monthly_listeners` integer COMMENT 'Cache, recomputed daily over a trailing 28 days',
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `genres` (
  `id` uuid PRIMARY KEY,
  `name` varchar(100) UNIQUE NOT NULL,
  `parent_id` uuid COMMENT 'e.g. Deep house under House under Electronic'
);

CREATE TABLE `releases` (
  `id` uuid PRIMARY KEY,
  `title` varchar(300) NOT NULL,
  `kind` ENUM ('album', 'single', 'ep', 'compilation') NOT NULL,
  `label_id` uuid COMMENT 'Null for a self-released record',
  `upc` varchar(14) UNIQUE COMMENT 'Universal Product Code, the identifier distributors and stores use for a release',
  `release_date` date NOT NULL,
  `original_release_date` date COMMENT 'Set for a remaster or reissue',
  `cover_art_key` varchar(300),
  `explicit` boolean NOT NULL DEFAULT false,
  `copyright_line` varchar(300) COMMENT 'The P line, e.g. "(P) 2024 Example Records"',
  `status` ENUM ('draft', 'scheduled', 'live', 'taken_down') NOT NULL DEFAULT 'draft',
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `release_artists` (
  `release_id` uuid NOT NULL,
  `artist_id` uuid NOT NULL,
  `position` smallint NOT NULL DEFAULT 1 COMMENT 'Display order of the headline artists',
  PRIMARY KEY (`release_id`, `artist_id`)
);

CREATE TABLE `tracks` (
  `id` uuid PRIMARY KEY,
  `title` varchar(300) NOT NULL,
  `version` varchar(100) COMMENT 'e.g. Radio edit, Live, 2011 Remaster',
  `isrc` char(12) UNIQUE COMMENT 'International Standard Recording Code: one per recording, the key royalty reports are matched on',
  `duration_ms` integer NOT NULL,
  `explicit` boolean NOT NULL DEFAULT false,
  `label_id` uuid COMMENT 'Owner of the sound recording, which can differ from the label of a compilation it appears on',
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `release_tracks` (
  `release_id` uuid NOT NULL,
  `track_id` uuid NOT NULL,
  `disc_number` smallint NOT NULL DEFAULT 1,
  `track_number` smallint NOT NULL,
  PRIMARY KEY (`release_id`, `track_id`)
);

CREATE TABLE `track_credits` (
  `track_id` uuid NOT NULL,
  `artist_id` uuid NOT NULL,
  `role` ENUM ('main', 'featured', 'producer', 'writer', 'composer', 'remixer') NOT NULL,
  `position` smallint NOT NULL DEFAULT 1 COMMENT 'Order within the role, so "A, B feat. C" renders in the right order',
  PRIMARY KEY (`track_id`, `artist_id`, `role`)
);

CREATE TABLE `track_genres` (
  `track_id` uuid NOT NULL,
  `genre_id` uuid NOT NULL,
  PRIMARY KEY (`track_id`, `genre_id`)
);

CREATE TABLE `labels` (
  `id` uuid PRIMARY KEY,
  `name` varchar(200) NOT NULL,
  `parent_label_id` uuid COMMENT 'For an imprint of a larger label group',
  `is_distributor` boolean NOT NULL DEFAULT false COMMENT 'Distributes on behalf of independent artists',
  `payout_account_token` varchar(200) COMMENT 'Bank account held by the payment processor'
);

CREATE TABLE `availability_windows` (
  `id` uuid PRIMARY KEY,
  `release_id` uuid NOT NULL,
  `territory` char(2) NOT NULL COMMENT 'ISO 3166-1 alpha-2 country code',
  `access` ENUM ('all_listeners', 'premium_only') NOT NULL COMMENT 'premium_only for a release windowed away from free listeners',
  `starts_at` timestamptz NOT NULL,
  `ends_at` timestamptz COMMENT 'Null for open-ended. Set it to take a release down without deleting anything.'
);

CREATE TABLE `audio_files` (
  `id` uuid PRIMARY KEY,
  `track_id` uuid NOT NULL,
  `codec` ENUM ('aac', 'ogg_vorbis', 'mp3', 'flac') NOT NULL,
  `bitrate_kbps` smallint NOT NULL COMMENT 'Nominal bitrate; the average for lossless',
  `sample_rate_hz` integer NOT NULL,
  `bit_depth` smallint COMMENT 'Lossless only, e.g. 16 or 24',
  `storage_key` varchar(300) NOT NULL COMMENT 'Object storage key. A CDN serves the file, never the database.',
  `size_bytes` bigint NOT NULL,
  `loudness_lufs` numeric(5,2) COMMENT 'Integrated loudness, for volume normalization between tracks',
  `is_preview` boolean NOT NULL DEFAULT false COMMENT '30-second clip for listeners without access'
);

CREATE TABLE `users` (
  `id` uuid PRIMARY KEY,
  `email` varchar(254) UNIQUE NOT NULL,
  `display_name` varchar(100) NOT NULL,
  `handle` varchar(30) UNIQUE,
  `country` char(2) NOT NULL COMMENT 'Licensing territory, set from billing or location and not freely editable',
  `birth_date` date COMMENT 'For explicit content defaults on minor accounts',
  `explicit_filter` boolean NOT NULL DEFAULT false,
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `subscription_plans` (
  `id` uuid PRIMARY KEY,
  `code` varchar(30) UNIQUE NOT NULL COMMENT 'e.g. individual, duo, family, student',
  `name` varchar(100) NOT NULL,
  `tier` ENUM ('free', 'premium') NOT NULL,
  `max_members` smallint NOT NULL DEFAULT 1 COMMENT 'Seats on the plan, e.g. 6 for a family plan',
  `max_bitrate_kbps` smallint NOT NULL,
  `offline_downloads` boolean NOT NULL DEFAULT false
);

CREATE TABLE `plan_prices` (
  `id` uuid PRIMARY KEY,
  `subscription_plan_id` uuid NOT NULL,
  `territory` char(2) NOT NULL,
  `currency` char(3) NOT NULL,
  `monthly_price_cents` integer NOT NULL,
  `valid_from` date NOT NULL,
  `valid_to` date
);

CREATE TABLE `subscriptions` (
  `id` uuid PRIMARY KEY,
  `owner_user_id` uuid NOT NULL COMMENT 'The payer',
  `subscription_plan_id` uuid NOT NULL,
  `plan_price_id` uuid NOT NULL COMMENT 'The price this subscription is billed at',
  `status` ENUM ('trialing', 'active', 'past_due', 'cancelled', 'expired') NOT NULL,
  `started_at` timestamptz NOT NULL,
  `current_period_end` timestamptz NOT NULL,
  `cancel_at_period_end` boolean NOT NULL DEFAULT false,
  `cancelled_at` timestamptz,
  `processor_reference` varchar(100) UNIQUE COMMENT 'Recurring billing is delegated to the payment processor'
);

CREATE TABLE `subscription_members` (
  `subscription_id` uuid NOT NULL,
  `user_id` uuid NOT NULL,
  `joined_at` timestamptz NOT NULL,
  `left_at` timestamptz,
  PRIMARY KEY (`subscription_id`, `user_id`)
);

CREATE TABLE `playlists` (
  `id` uuid PRIMARY KEY,
  `owner_user_id` uuid COMMENT 'Null for an editorial playlist owned by the service',
  `title` varchar(200) NOT NULL,
  `description` varchar(1000),
  `is_public` boolean NOT NULL DEFAULT true,
  `is_collaborative` boolean NOT NULL DEFAULT false,
  `cover_image_key` varchar(300),
  `follower_count` integer NOT NULL DEFAULT 0 COMMENT 'Cache of follows',
  `created_at` timestamptz NOT NULL DEFAULT (now()),
  `updated_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `playlist_tracks` (
  `id` uuid PRIMARY KEY COMMENT 'Own id, because the same track can appear twice in one playlist',
  `playlist_id` uuid NOT NULL,
  `track_id` uuid NOT NULL,
  `rank` varchar(64) NOT NULL COMMENT 'Lexicographic sort key. A move writes one new key that sorts between the new neighbours.',
  `added_by` uuid COMMENT 'Who added it, which matters on a collaborative playlist',
  `added_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `playlist_collaborators` (
  `playlist_id` uuid NOT NULL,
  `user_id` uuid NOT NULL,
  `invited_at` timestamptz NOT NULL DEFAULT (now()),
  PRIMARY KEY (`playlist_id`, `user_id`)
);

CREATE TABLE `follows` (
  `id` uuid PRIMARY KEY,
  `follower_id` uuid NOT NULL,
  `followed_user_id` uuid,
  `followed_artist_id` uuid,
  `followed_playlist_id` uuid,
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `library_saves` (
  `id` uuid PRIMARY KEY,
  `user_id` uuid NOT NULL,
  `track_id` uuid,
  `release_id` uuid,
  `saved_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `devices` (
  `id` uuid PRIMARY KEY,
  `user_id` uuid NOT NULL,
  `kind` ENUM ('phone', 'tablet', 'desktop', 'web', 'speaker', 'car', 'tv') NOT NULL,
  `name` varchar(100) COMMENT 'e.g. Kitchen speaker',
  `app_version` varchar(30),
  `last_seen_at` timestamptz
);

CREATE TABLE `play_events` (
  `user_id` uuid NOT NULL,
  `played_at` timestamptz NOT NULL COMMENT 'When playback started; device time for offline plays',
  `track_id` uuid NOT NULL,
  `device_id` uuid,
  `ms_played` integer NOT NULL,
  `is_qualified` boolean NOT NULL COMMENT 'Played at least 30 seconds, the usual threshold for a stream to count toward royalties',
  `end_reason` ENUM ('finished', 'skipped', 'stopped', 'error') NOT NULL,
  `context_kind` ENUM ('release', 'playlist', 'artist', 'radio', 'search', 'library') NOT NULL,
  `context_id` uuid COMMENT 'The playlist, release or artist it was played from, per context_kind',
  `territory` char(2) NOT NULL COMMENT 'Copied from the user at play time',
  `plan_tier` ENUM ('free', 'premium') NOT NULL COMMENT 'Copied at play time: free and premium streams are paid from different pools',
  `offline` boolean NOT NULL DEFAULT false COMMENT 'Played offline and uploaded on the next sync',
  PRIMARY KEY (`user_id`, `played_at`, `track_id`)
);

CREATE TABLE `play_counts` (
  `track_id` uuid NOT NULL,
  `period_date` date NOT NULL COMMENT 'One row per day; months are sums of days',
  `territory` char(2) NOT NULL,
  `plan_tier` ENUM ('free', 'premium') NOT NULL,
  `streams` integer NOT NULL COMMENT 'Every play, however short',
  `qualified_streams` integer NOT NULL COMMENT 'Plays of 30 seconds or more; royalties are paid on these',
  `unique_listeners` integer NOT NULL COMMENT 'Does NOT sum across days; monthly listeners need their own rollup',
  PRIMARY KEY (`track_id`, `period_date`, `territory`, `plan_tier`)
);

CREATE TABLE `royalty_pools` (
  `id` uuid PRIMARY KEY,
  `period_month` date NOT NULL COMMENT 'First day of the month',
  `territory` char(2) NOT NULL,
  `plan_tier` ENUM ('free', 'premium') NOT NULL,
  `currency` char(3) NOT NULL,
  `net_revenue_cents` bigint NOT NULL COMMENT 'Subscription or ad revenue for the territory and tier, after tax',
  `rights_share_bps` integer NOT NULL COMMENT 'Share of revenue paid out to rights holders',
  `total_qualified_streams` bigint NOT NULL,
  `status` ENUM ('draft', 'final', 'paid') NOT NULL DEFAULT 'draft',
  `computed_at` timestamptz
);

CREATE TABLE `royalty_statements` (
  `id` uuid PRIMARY KEY,
  `royalty_pool_id` uuid NOT NULL,
  `label_id` uuid NOT NULL,
  `qualified_streams` bigint NOT NULL COMMENT 'Sum of play_counts for tracks this label owns, in the pool',
  `amount_cents` bigint NOT NULL COMMENT 'qualified_streams times the pool rate',
  `currency` char(3) NOT NULL,
  `issued_at` timestamptz,
  `paid_at` timestamptz,
  `processor_reference` varchar(100) UNIQUE
);

CREATE UNIQUE INDEX `release_tracks_index_0` ON `release_tracks` (`release_id`, `disc_number`, `track_number`);

CREATE INDEX `track_credits_index_1` ON `track_credits` (`artist_id`, `role`);

CREATE UNIQUE INDEX `availability_windows_index_2` ON `availability_windows` (`release_id`, `territory`, `starts_at`);

CREATE UNIQUE INDEX `audio_files_index_3` ON `audio_files` (`track_id`, `codec`, `bitrate_kbps`, `is_preview`);

CREATE UNIQUE INDEX `plan_prices_index_4` ON `plan_prices` (`subscription_plan_id`, `territory`, `valid_from`);

CREATE INDEX `one_live_subscription` ON `subscriptions` (`owner_user_id`);

CREATE INDEX `one_current_plan` ON `subscription_members` (`user_id`);

CREATE UNIQUE INDEX `playlist_tracks_index_7` ON `playlist_tracks` (`playlist_id`, `rank`);

CREATE UNIQUE INDEX `follows_index_8` ON `follows` (`follower_id`, `followed_user_id`);

CREATE UNIQUE INDEX `follows_index_9` ON `follows` (`follower_id`, `followed_artist_id`);

CREATE UNIQUE INDEX `follows_index_10` ON `follows` (`follower_id`, `followed_playlist_id`);

CREATE INDEX `follows_index_11` ON `follows` (`followed_artist_id`);

CREATE UNIQUE INDEX `library_saves_index_12` ON `library_saves` (`user_id`, `track_id`);

CREATE UNIQUE INDEX `library_saves_index_13` ON `library_saves` (`user_id`, `release_id`);

CREATE INDEX `library_saves_index_14` ON `library_saves` (`user_id`, `saved_at`);

CREATE INDEX `play_events_index_15` ON `play_events` (`track_id`, `played_at`);

CREATE INDEX `play_counts_index_16` ON `play_counts` (`period_date`, `territory`, `plan_tier`);

CREATE UNIQUE INDEX `royalty_pools_index_17` ON `royalty_pools` (`period_month`, `territory`, `plan_tier`);

CREATE UNIQUE INDEX `royalty_statements_index_18` ON `royalty_statements` (`royalty_pool_id`, `label_id`);

ALTER TABLE `artists` COMMENT = 'Performers, bands, producers and writers: anyone who can be credited on a track or a release.';

ALTER TABLE `genres` COMMENT = 'A genre tree. Browsing a parent includes its children.';

ALTER TABLE `releases` COMMENT = 'An album, single, EP or compilation: the product people browse and save. It has a tracklist; it holds no audio itself.';

ALTER TABLE `release_artists` COMMENT = 'Headline artists of a release, which can differ from the track credits; a compilation has none and shows as Various Artists.';

ALTER TABLE `tracks` COMMENT = 'A recording. The same song on the single and on the album is ONE track, with one play count and one royalty line.';

ALTER TABLE `release_tracks` COMMENT = 'The tracklist: which recordings appear on a release, on which disc, in which position.';

ALTER TABLE `track_credits` COMMENT = 'Many artists per track, each with a role. The display string "A feat. B" is rendered from these rows, never stored, so a featured artist page finds the track too.';

ALTER TABLE `track_genres` COMMENT = 'Genres per track. A release shows the genres of its tracks.';

ALTER TABLE `labels` COMMENT = 'Rights holders for the sound recordings: labels, their imprints, and distributors acting for independent artists. Royalty statements are issued to them.';

ALTER TABLE `availability_windows` COMMENT = 'Where and when a release may be streamed under its license. A track plays only if a window for one of its releases covers the listener territory, plan and the current time.';

ALTER TABLE `audio_files` COMMENT = 'One encoding of a track. The player picks a file by plan quality and network conditions.';

ALTER TABLE `users` COMMENT = 'Listeners. A user is on the free tier unless a live subscription says otherwise.';

ALTER TABLE `subscription_plans` COMMENT = 'What can be bought. Prices live per territory in plan_prices.';

ALTER TABLE `plan_prices` COMMENT = 'Plan prices per country, versioned. A subscription keeps the price it was sold at until it is deliberately moved to a new one.';

ALTER TABLE `subscriptions` COMMENT = 'A paid plan. Its revenue feeds the royalty pool for its territory and tier.';

ALTER TABLE `subscription_members` COMMENT = 'Who shares a duo or family plan, owner included. Premium access for each member comes from this row, so leaving the plan drops that member to free.';

ALTER TABLE `playlists` COMMENT = 'User and editorial playlists.';

ALTER TABLE `playlist_tracks` COMMENT = 'The ordered entries of a playlist. Dragging track 900 to the top of a 1,000-track playlist updates one row, not a thousand position numbers.';

ALTER TABLE `playlist_collaborators` COMMENT = 'Who besides the owner may edit a collaborative playlist.';

ALTER TABLE `follows` COMMENT = 'Users following users, artists or playlists. One nullable foreign key per target, with a check constraint that exactly one is set, instead of a generic target_id: every follow is a real, enforced foreign key.';

ALTER TABLE `library_saves` COMMENT = 'Liked songs and saved albums, with the same exactly-one-target pattern as follows. Saving an album does not save each of its tracks.';

ALTER TABLE `devices` COMMENT = 'Where a user listens. Concurrent stream limits and offline download limits are enforced per device.';

ALTER TABLE `play_events` COMMENT = 'Append-only: one row each time playback stops, from every listener, and larger than every other table combined.
Partition by played_at (monthly), write in batches from the event pipeline, never update a row, and detach old partitions to cold storage.
Territory and plan tier are copied onto the event so royalties never depend on what the user looks like today. Reports read play_counts, never this table.';

ALTER TABLE `play_counts` COMMENT = 'Daily rollup of play_events per track, territory and tier, rebuilt idempotently for a whole day by a batch job. Charts, artist dashboards and royalty runs read this table.';

ALTER TABLE `royalty_pools` COMMENT = 'The pro-rata royalty model: each month the revenue of a territory and tier is pooled, and the per-stream rate is net revenue times rights share divided by total qualified streams.';

ALTER TABLE `royalty_statements` COMMENT = 'What each rights holder is owed from one pool. A statement is issued once its pool is final and never edited after payment; a correction goes on a later statement.';

ALTER TABLE `genres` ADD FOREIGN KEY (`parent_id`) REFERENCES `genres` (`id`);

ALTER TABLE `releases` ADD FOREIGN KEY (`label_id`) REFERENCES `labels` (`id`);

ALTER TABLE `release_artists` ADD FOREIGN KEY (`release_id`) REFERENCES `releases` (`id`);

ALTER TABLE `release_artists` ADD FOREIGN KEY (`artist_id`) REFERENCES `artists` (`id`);

ALTER TABLE `tracks` ADD FOREIGN KEY (`label_id`) REFERENCES `labels` (`id`);

ALTER TABLE `release_tracks` ADD FOREIGN KEY (`release_id`) REFERENCES `releases` (`id`);

ALTER TABLE `release_tracks` ADD FOREIGN KEY (`track_id`) REFERENCES `tracks` (`id`);

ALTER TABLE `track_credits` ADD FOREIGN KEY (`track_id`) REFERENCES `tracks` (`id`);

ALTER TABLE `track_credits` ADD FOREIGN KEY (`artist_id`) REFERENCES `artists` (`id`);

ALTER TABLE `track_genres` ADD FOREIGN KEY (`track_id`) REFERENCES `tracks` (`id`);

ALTER TABLE `track_genres` ADD FOREIGN KEY (`genre_id`) REFERENCES `genres` (`id`);

ALTER TABLE `labels` ADD FOREIGN KEY (`parent_label_id`) REFERENCES `labels` (`id`);

ALTER TABLE `availability_windows` ADD FOREIGN KEY (`release_id`) REFERENCES `releases` (`id`);

ALTER TABLE `audio_files` ADD FOREIGN KEY (`track_id`) REFERENCES `tracks` (`id`);

ALTER TABLE `plan_prices` ADD FOREIGN KEY (`subscription_plan_id`) REFERENCES `subscription_plans` (`id`);

ALTER TABLE `subscriptions` ADD FOREIGN KEY (`owner_user_id`) REFERENCES `users` (`id`);

ALTER TABLE `subscriptions` ADD FOREIGN KEY (`subscription_plan_id`) REFERENCES `subscription_plans` (`id`);

ALTER TABLE `subscriptions` ADD FOREIGN KEY (`plan_price_id`) REFERENCES `plan_prices` (`id`);

ALTER TABLE `subscription_members` ADD FOREIGN KEY (`subscription_id`) REFERENCES `subscriptions` (`id`);

ALTER TABLE `subscription_members` ADD FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);

ALTER TABLE `playlists` ADD FOREIGN KEY (`owner_user_id`) REFERENCES `users` (`id`);

ALTER TABLE `playlist_tracks` ADD FOREIGN KEY (`playlist_id`) REFERENCES `playlists` (`id`);

ALTER TABLE `playlist_tracks` ADD FOREIGN KEY (`track_id`) REFERENCES `tracks` (`id`);

ALTER TABLE `playlist_tracks` ADD FOREIGN KEY (`added_by`) REFERENCES `users` (`id`);

ALTER TABLE `playlist_collaborators` ADD FOREIGN KEY (`playlist_id`) REFERENCES `playlists` (`id`);

ALTER TABLE `playlist_collaborators` ADD FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);

ALTER TABLE `follows` ADD FOREIGN KEY (`follower_id`) REFERENCES `users` (`id`);

ALTER TABLE `follows` ADD FOREIGN KEY (`followed_user_id`) REFERENCES `users` (`id`);

ALTER TABLE `follows` ADD FOREIGN KEY (`followed_artist_id`) REFERENCES `artists` (`id`);

ALTER TABLE `follows` ADD FOREIGN KEY (`followed_playlist_id`) REFERENCES `playlists` (`id`);

ALTER TABLE `library_saves` ADD FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);

ALTER TABLE `library_saves` ADD FOREIGN KEY (`track_id`) REFERENCES `tracks` (`id`);

ALTER TABLE `library_saves` ADD FOREIGN KEY (`release_id`) REFERENCES `releases` (`id`);

ALTER TABLE `devices` ADD FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);

ALTER TABLE `play_events` ADD FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);

ALTER TABLE `play_events` ADD FOREIGN KEY (`track_id`) REFERENCES `tracks` (`id`);

ALTER TABLE `play_events` ADD FOREIGN KEY (`device_id`) REFERENCES `devices` (`id`);

ALTER TABLE `play_counts` ADD FOREIGN KEY (`track_id`) REFERENCES `tracks` (`id`);

ALTER TABLE `royalty_statements` ADD FOREIGN KEY (`royalty_pool_id`) REFERENCES `royalty_pools` (`id`);

ALTER TABLE `royalty_statements` ADD FOREIGN KEY (`label_id`) REFERENCES `labels` (`id`);
SQL Server
sql-server.sql SQL Server
CREATE TABLE [artists] (
  [id] uuid PRIMARY KEY,
  [name] varchar(200) NOT NULL,
  [sort_name] varchar(200) NOT NULL,
  [slug] varchar(200) UNIQUE NOT NULL,
  [bio] text,
  [country] char(2),
  [image_key] varchar(300),
  [is_verified] boolean NOT NULL DEFAULT (false),
  [monthly_listeners] integer,
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [genres] (
  [id] uuid PRIMARY KEY,
  [name] varchar(100) UNIQUE NOT NULL,
  [parent_id] uuid
)
GO

CREATE TABLE [releases] (
  [id] uuid PRIMARY KEY,
  [title] varchar(300) NOT NULL,
  [kind] nvarchar(255) NOT NULL CHECK ([kind] IN ('album', 'single', 'ep', 'compilation')),
  [label_id] uuid,
  [upc] varchar(14) UNIQUE,
  [release_date] date NOT NULL,
  [original_release_date] date,
  [cover_art_key] varchar(300),
  [explicit] boolean NOT NULL DEFAULT (false),
  [copyright_line] varchar(300),
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('draft', 'scheduled', 'live', 'taken_down')) DEFAULT 'draft',
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [release_artists] (
  [release_id] uuid NOT NULL,
  [artist_id] uuid NOT NULL,
  [position] smallint NOT NULL DEFAULT (1),
  PRIMARY KEY ([release_id], [artist_id])
)
GO

CREATE TABLE [tracks] (
  [id] uuid PRIMARY KEY,
  [title] varchar(300) NOT NULL,
  [version] varchar(100),
  [isrc] char(12) UNIQUE,
  [duration_ms] integer NOT NULL,
  [explicit] boolean NOT NULL DEFAULT (false),
  [label_id] uuid,
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [release_tracks] (
  [release_id] uuid NOT NULL,
  [track_id] uuid NOT NULL,
  [disc_number] smallint NOT NULL DEFAULT (1),
  [track_number] smallint NOT NULL,
  PRIMARY KEY ([release_id], [track_id])
)
GO

CREATE TABLE [track_credits] (
  [track_id] uuid NOT NULL,
  [artist_id] uuid NOT NULL,
  [role] nvarchar(255) NOT NULL CHECK ([role] IN ('main', 'featured', 'producer', 'writer', 'composer', 'remixer')),
  [position] smallint NOT NULL DEFAULT (1),
  PRIMARY KEY ([track_id], [artist_id], [role])
)
GO

CREATE TABLE [track_genres] (
  [track_id] uuid NOT NULL,
  [genre_id] uuid NOT NULL,
  PRIMARY KEY ([track_id], [genre_id])
)
GO

CREATE TABLE [labels] (
  [id] uuid PRIMARY KEY,
  [name] varchar(200) NOT NULL,
  [parent_label_id] uuid,
  [is_distributor] boolean NOT NULL DEFAULT (false),
  [payout_account_token] varchar(200)
)
GO

CREATE TABLE [availability_windows] (
  [id] uuid PRIMARY KEY,
  [release_id] uuid NOT NULL,
  [territory] char(2) NOT NULL,
  [access] nvarchar(255) NOT NULL CHECK ([access] IN ('all_listeners', 'premium_only')),
  [starts_at] timestamptz NOT NULL,
  [ends_at] timestamptz
)
GO

CREATE TABLE [audio_files] (
  [id] uuid PRIMARY KEY,
  [track_id] uuid NOT NULL,
  [codec] nvarchar(255) NOT NULL CHECK ([codec] IN ('aac', 'ogg_vorbis', 'mp3', 'flac')),
  [bitrate_kbps] smallint NOT NULL,
  [sample_rate_hz] integer NOT NULL,
  [bit_depth] smallint,
  [storage_key] varchar(300) NOT NULL,
  [size_bytes] bigint NOT NULL,
  [loudness_lufs] numeric(5,2),
  [is_preview] boolean NOT NULL DEFAULT (false)
)
GO

CREATE TABLE [users] (
  [id] uuid PRIMARY KEY,
  [email] varchar(254) UNIQUE NOT NULL,
  [display_name] varchar(100) NOT NULL,
  [handle] varchar(30) UNIQUE,
  [country] char(2) NOT NULL,
  [birth_date] date,
  [explicit_filter] boolean NOT NULL DEFAULT (false),
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [subscription_plans] (
  [id] uuid PRIMARY KEY,
  [code] varchar(30) UNIQUE NOT NULL,
  [name] varchar(100) NOT NULL,
  [tier] nvarchar(255) NOT NULL CHECK ([tier] IN ('free', 'premium')),
  [max_members] smallint NOT NULL DEFAULT (1),
  [max_bitrate_kbps] smallint NOT NULL,
  [offline_downloads] boolean NOT NULL DEFAULT (false)
)
GO

CREATE TABLE [plan_prices] (
  [id] uuid PRIMARY KEY,
  [subscription_plan_id] uuid NOT NULL,
  [territory] char(2) NOT NULL,
  [currency] char(3) NOT NULL,
  [monthly_price_cents] integer NOT NULL,
  [valid_from] date NOT NULL,
  [valid_to] date
)
GO

CREATE TABLE [subscriptions] (
  [id] uuid PRIMARY KEY,
  [owner_user_id] uuid NOT NULL,
  [subscription_plan_id] uuid NOT NULL,
  [plan_price_id] uuid NOT NULL,
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('trialing', 'active', 'past_due', 'cancelled', 'expired')),
  [started_at] timestamptz NOT NULL,
  [current_period_end] timestamptz NOT NULL,
  [cancel_at_period_end] boolean NOT NULL DEFAULT (false),
  [cancelled_at] timestamptz,
  [processor_reference] varchar(100) UNIQUE
)
GO

CREATE TABLE [subscription_members] (
  [subscription_id] uuid NOT NULL,
  [user_id] uuid NOT NULL,
  [joined_at] timestamptz NOT NULL,
  [left_at] timestamptz,
  PRIMARY KEY ([subscription_id], [user_id])
)
GO

CREATE TABLE [playlists] (
  [id] uuid PRIMARY KEY,
  [owner_user_id] uuid,
  [title] varchar(200) NOT NULL,
  [description] varchar(1000),
  [is_public] boolean NOT NULL DEFAULT (true),
  [is_collaborative] boolean NOT NULL DEFAULT (false),
  [cover_image_key] varchar(300),
  [follower_count] integer NOT NULL DEFAULT (0),
  [created_at] timestamptz NOT NULL DEFAULT (now()),
  [updated_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [playlist_tracks] (
  [id] uuid PRIMARY KEY,
  [playlist_id] uuid NOT NULL,
  [track_id] uuid NOT NULL,
  [rank] varchar(64) NOT NULL,
  [added_by] uuid,
  [added_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [playlist_collaborators] (
  [playlist_id] uuid NOT NULL,
  [user_id] uuid NOT NULL,
  [invited_at] timestamptz NOT NULL DEFAULT (now()),
  PRIMARY KEY ([playlist_id], [user_id])
)
GO

CREATE TABLE [follows] (
  [id] uuid PRIMARY KEY,
  [follower_id] uuid NOT NULL,
  [followed_user_id] uuid,
  [followed_artist_id] uuid,
  [followed_playlist_id] uuid,
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [library_saves] (
  [id] uuid PRIMARY KEY,
  [user_id] uuid NOT NULL,
  [track_id] uuid,
  [release_id] uuid,
  [saved_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [devices] (
  [id] uuid PRIMARY KEY,
  [user_id] uuid NOT NULL,
  [kind] nvarchar(255) NOT NULL CHECK ([kind] IN ('phone', 'tablet', 'desktop', 'web', 'speaker', 'car', 'tv')),
  [name] varchar(100),
  [app_version] varchar(30),
  [last_seen_at] timestamptz
)
GO

CREATE TABLE [play_events] (
  [user_id] uuid NOT NULL,
  [played_at] timestamptz NOT NULL,
  [track_id] uuid NOT NULL,
  [device_id] uuid,
  [ms_played] integer NOT NULL,
  [is_qualified] boolean NOT NULL,
  [end_reason] nvarchar(255) NOT NULL CHECK ([end_reason] IN ('finished', 'skipped', 'stopped', 'error')),
  [context_kind] nvarchar(255) NOT NULL CHECK ([context_kind] IN ('release', 'playlist', 'artist', 'radio', 'search', 'library')),
  [context_id] uuid,
  [territory] char(2) NOT NULL,
  [plan_tier] nvarchar(255) NOT NULL CHECK ([plan_tier] IN ('free', 'premium')),
  [offline] boolean NOT NULL DEFAULT (false),
  PRIMARY KEY ([user_id], [played_at], [track_id])
)
GO

CREATE TABLE [play_counts] (
  [track_id] uuid NOT NULL,
  [period_date] date NOT NULL,
  [territory] char(2) NOT NULL,
  [plan_tier] nvarchar(255) NOT NULL CHECK ([plan_tier] IN ('free', 'premium')),
  [streams] integer NOT NULL,
  [qualified_streams] integer NOT NULL,
  [unique_listeners] integer NOT NULL,
  PRIMARY KEY ([track_id], [period_date], [territory], [plan_tier])
)
GO

CREATE TABLE [royalty_pools] (
  [id] uuid PRIMARY KEY,
  [period_month] date NOT NULL,
  [territory] char(2) NOT NULL,
  [plan_tier] nvarchar(255) NOT NULL CHECK ([plan_tier] IN ('free', 'premium')),
  [currency] char(3) NOT NULL,
  [net_revenue_cents] bigint NOT NULL,
  [rights_share_bps] integer NOT NULL,
  [total_qualified_streams] bigint NOT NULL,
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('draft', 'final', 'paid')) DEFAULT 'draft',
  [computed_at] timestamptz
)
GO

CREATE TABLE [royalty_statements] (
  [id] uuid PRIMARY KEY,
  [royalty_pool_id] uuid NOT NULL,
  [label_id] uuid NOT NULL,
  [qualified_streams] bigint NOT NULL,
  [amount_cents] bigint NOT NULL,
  [currency] char(3) NOT NULL,
  [issued_at] timestamptz,
  [paid_at] timestamptz,
  [processor_reference] varchar(100) UNIQUE
)
GO

CREATE UNIQUE INDEX [release_tracks_index_0] ON [release_tracks] ("release_id", "disc_number", "track_number")
GO

CREATE INDEX [track_credits_index_1] ON [track_credits] ("artist_id", "role")
GO

CREATE UNIQUE INDEX [availability_windows_index_2] ON [availability_windows] ("release_id", "territory", "starts_at")
GO

CREATE UNIQUE INDEX [audio_files_index_3] ON [audio_files] ("track_id", "codec", "bitrate_kbps", "is_preview")
GO

CREATE UNIQUE INDEX [plan_prices_index_4] ON [plan_prices] ("subscription_plan_id", "territory", "valid_from")
GO

CREATE INDEX [one_live_subscription] ON [subscriptions] ("owner_user_id")
GO

CREATE INDEX [one_current_plan] ON [subscription_members] ("user_id")
GO

CREATE UNIQUE INDEX [playlist_tracks_index_7] ON [playlist_tracks] ("playlist_id", "rank")
GO

CREATE UNIQUE INDEX [follows_index_8] ON [follows] ("follower_id", "followed_user_id")
GO

CREATE UNIQUE INDEX [follows_index_9] ON [follows] ("follower_id", "followed_artist_id")
GO

CREATE UNIQUE INDEX [follows_index_10] ON [follows] ("follower_id", "followed_playlist_id")
GO

CREATE INDEX [follows_index_11] ON [follows] ("followed_artist_id")
GO

CREATE UNIQUE INDEX [library_saves_index_12] ON [library_saves] ("user_id", "track_id")
GO

CREATE UNIQUE INDEX [library_saves_index_13] ON [library_saves] ("user_id", "release_id")
GO

CREATE INDEX [library_saves_index_14] ON [library_saves] ("user_id", "saved_at")
GO

CREATE INDEX [play_events_index_15] ON [play_events] ("track_id", "played_at")
GO

CREATE INDEX [play_counts_index_16] ON [play_counts] ("period_date", "territory", "plan_tier")
GO

CREATE UNIQUE INDEX [royalty_pools_index_17] ON [royalty_pools] ("period_month", "territory", "plan_tier")
GO

CREATE UNIQUE INDEX [royalty_statements_index_18] ON [royalty_statements] ("royalty_pool_id", "label_id")
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Performers, bands, producers and writers: anyone who can be credited on a track or a release.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'artists';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'For A to Z browsing, e.g. "Midnight Owls, The"',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'artists',
@level2type = N'Column', @level2name = 'sort_name';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Object storage key',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'artists',
@level2type = N'Column', @level2name = 'image_key';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Cache, recomputed daily over a trailing 28 days',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'artists',
@level2type = N'Column', @level2name = 'monthly_listeners';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'A genre tree. Browsing a parent includes its children.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'genres';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. Deep house under House under Electronic',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'genres',
@level2type = N'Column', @level2name = 'parent_id';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'An album, single, EP or compilation: the product people browse and save. It has a tracklist; it holds no audio itself.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'releases';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null for a self-released record',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'releases',
@level2type = N'Column', @level2name = 'label_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Universal Product Code, the identifier distributors and stores use for a release',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'releases',
@level2type = N'Column', @level2name = 'upc';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Set for a remaster or reissue',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'releases',
@level2type = N'Column', @level2name = 'original_release_date';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'The P line, e.g. "(P) 2024 Example Records"',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'releases',
@level2type = N'Column', @level2name = 'copyright_line';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Headline artists of a release, which can differ from the track credits; a compilation has none and shows as Various Artists.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'release_artists';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Display order of the headline artists',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'release_artists',
@level2type = N'Column', @level2name = 'position';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'A recording. The same song on the single and on the album is ONE track, with one play count and one royalty line.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'tracks';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. Radio edit, Live, 2011 Remaster',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'tracks',
@level2type = N'Column', @level2name = 'version';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'International Standard Recording Code: one per recording, the key royalty reports are matched on',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'tracks',
@level2type = N'Column', @level2name = 'isrc';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Owner of the sound recording, which can differ from the label of a compilation it appears on',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'tracks',
@level2type = N'Column', @level2name = 'label_id';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'The tracklist: which recordings appear on a release, on which disc, in which position.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'release_tracks';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Many artists per track, each with a role. The display string "A feat. B" is rendered from these rows, never stored, so a featured artist page finds the track too.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'track_credits';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Order within the role, so "A, B feat. C" renders in the right order',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'track_credits',
@level2type = N'Column', @level2name = 'position';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Genres per track. A release shows the genres of its tracks.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'track_genres';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Rights holders for the sound recordings: labels, their imprints, and distributors acting for independent artists. Royalty statements are issued to them.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'labels';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'For an imprint of a larger label group',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'labels',
@level2type = N'Column', @level2name = 'parent_label_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Distributes on behalf of independent artists',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'labels',
@level2type = N'Column', @level2name = 'is_distributor';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Bank account held by the payment processor',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'labels',
@level2type = N'Column', @level2name = 'payout_account_token';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Where and when a release may be streamed under its license. A track plays only if a window for one of its releases covers the listener territory, plan and the current time.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'availability_windows';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'ISO 3166-1 alpha-2 country code',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'availability_windows',
@level2type = N'Column', @level2name = 'territory';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'premium_only for a release windowed away from free listeners',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'availability_windows',
@level2type = N'Column', @level2name = 'access';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null for open-ended. Set it to take a release down without deleting anything.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'availability_windows',
@level2type = N'Column', @level2name = 'ends_at';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'One encoding of a track. The player picks a file by plan quality and network conditions.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'audio_files';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Nominal bitrate; the average for lossless',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'audio_files',
@level2type = N'Column', @level2name = 'bitrate_kbps';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Lossless only, e.g. 16 or 24',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'audio_files',
@level2type = N'Column', @level2name = 'bit_depth';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Object storage key. A CDN serves the file, never the database.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'audio_files',
@level2type = N'Column', @level2name = 'storage_key';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Integrated loudness, for volume normalization between tracks',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'audio_files',
@level2type = N'Column', @level2name = 'loudness_lufs';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = '30-second clip for listeners without access',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'audio_files',
@level2type = N'Column', @level2name = 'is_preview';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Listeners. A user is on the free tier unless a live subscription says otherwise.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'users';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Licensing territory, set from billing or location and not freely editable',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'users',
@level2type = N'Column', @level2name = 'country';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'For explicit content defaults on minor accounts',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'users',
@level2type = N'Column', @level2name = 'birth_date';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'What can be bought. Prices live per territory in plan_prices.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'subscription_plans';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. individual, duo, family, student',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'subscription_plans',
@level2type = N'Column', @level2name = 'code';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Seats on the plan, e.g. 6 for a family plan',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'subscription_plans',
@level2type = N'Column', @level2name = 'max_members';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Plan prices per country, versioned. A subscription keeps the price it was sold at until it is deliberately moved to a new one.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'plan_prices';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'A paid plan. Its revenue feeds the royalty pool for its territory and tier.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'subscriptions';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'The payer',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'subscriptions',
@level2type = N'Column', @level2name = 'owner_user_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'The price this subscription is billed at',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'subscriptions',
@level2type = N'Column', @level2name = 'plan_price_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Recurring billing is delegated to the payment processor',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'subscriptions',
@level2type = N'Column', @level2name = 'processor_reference';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Who shares a duo or family plan, owner included. Premium access for each member comes from this row, so leaving the plan drops that member to free.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'subscription_members';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'User and editorial playlists.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'playlists';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null for an editorial playlist owned by the service',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'playlists',
@level2type = N'Column', @level2name = 'owner_user_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Cache of follows',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'playlists',
@level2type = N'Column', @level2name = 'follower_count';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'The ordered entries of a playlist. Dragging track 900 to the top of a 1,000-track playlist updates one row, not a thousand position numbers.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'playlist_tracks';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Own id, because the same track can appear twice in one playlist',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'playlist_tracks',
@level2type = N'Column', @level2name = 'id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Lexicographic sort key. A move writes one new key that sorts between the new neighbours.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'playlist_tracks',
@level2type = N'Column', @level2name = 'rank';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Who added it, which matters on a collaborative playlist',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'playlist_tracks',
@level2type = N'Column', @level2name = 'added_by';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Who besides the owner may edit a collaborative playlist.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'playlist_collaborators';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Users following users, artists or playlists. One nullable foreign key per target, with a check constraint that exactly one is set, instead of a generic target_id: every follow is a real, enforced foreign key.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'follows';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Liked songs and saved albums, with the same exactly-one-target pattern as follows. Saving an album does not save each of its tracks.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'library_saves';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Where a user listens. Concurrent stream limits and offline download limits are enforced per device.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'devices';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. Kitchen speaker',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'devices',
@level2type = N'Column', @level2name = 'name';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Append-only: one row each time playback stops, from every listener, and larger than every other table combined.
Partition by played_at (monthly), write in batches from the event pipeline, never update a row, and detach old partitions to cold storage.
Territory and plan tier are copied onto the event so royalties never depend on what the user looks like today. Reports read play_counts, never this table.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'play_events';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'When playback started; device time for offline plays',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'play_events',
@level2type = N'Column', @level2name = 'played_at';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Played at least 30 seconds, the usual threshold for a stream to count toward royalties',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'play_events',
@level2type = N'Column', @level2name = 'is_qualified';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'The playlist, release or artist it was played from, per context_kind',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'play_events',
@level2type = N'Column', @level2name = 'context_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Copied from the user at play time',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'play_events',
@level2type = N'Column', @level2name = 'territory';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Copied at play time: free and premium streams are paid from different pools',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'play_events',
@level2type = N'Column', @level2name = 'plan_tier';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Played offline and uploaded on the next sync',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'play_events',
@level2type = N'Column', @level2name = 'offline';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Daily rollup of play_events per track, territory and tier, rebuilt idempotently for a whole day by a batch job. Charts, artist dashboards and royalty runs read this table.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'play_counts';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'One row per day; months are sums of days',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'play_counts',
@level2type = N'Column', @level2name = 'period_date';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Every play, however short',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'play_counts',
@level2type = N'Column', @level2name = 'streams';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Plays of 30 seconds or more; royalties are paid on these',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'play_counts',
@level2type = N'Column', @level2name = 'qualified_streams';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Does NOT sum across days; monthly listeners need their own rollup',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'play_counts',
@level2type = N'Column', @level2name = 'unique_listeners';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'The pro-rata royalty model: each month the revenue of a territory and tier is pooled, and the per-stream rate is net revenue times rights share divided by total qualified streams.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'royalty_pools';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'First day of the month',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'royalty_pools',
@level2type = N'Column', @level2name = 'period_month';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Subscription or ad revenue for the territory and tier, after tax',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'royalty_pools',
@level2type = N'Column', @level2name = 'net_revenue_cents';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Share of revenue paid out to rights holders',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'royalty_pools',
@level2type = N'Column', @level2name = 'rights_share_bps';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'What each rights holder is owed from one pool. A statement is issued once its pool is final and never edited after payment; a correction goes on a later statement.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'royalty_statements';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Sum of play_counts for tracks this label owns, in the pool',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'royalty_statements',
@level2type = N'Column', @level2name = 'qualified_streams';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'qualified_streams times the pool rate',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'royalty_statements',
@level2type = N'Column', @level2name = 'amount_cents';
GO

ALTER TABLE [genres] ADD FOREIGN KEY ([parent_id]) REFERENCES [genres] ([id])
GO

ALTER TABLE [releases] ADD FOREIGN KEY ([label_id]) REFERENCES [labels] ([id])
GO

ALTER TABLE [release_artists] ADD FOREIGN KEY ([release_id]) REFERENCES [releases] ([id])
GO

ALTER TABLE [release_artists] ADD FOREIGN KEY ([artist_id]) REFERENCES [artists] ([id])
GO

ALTER TABLE [tracks] ADD FOREIGN KEY ([label_id]) REFERENCES [labels] ([id])
GO

ALTER TABLE [release_tracks] ADD FOREIGN KEY ([release_id]) REFERENCES [releases] ([id])
GO

ALTER TABLE [release_tracks] ADD FOREIGN KEY ([track_id]) REFERENCES [tracks] ([id])
GO

ALTER TABLE [track_credits] ADD FOREIGN KEY ([track_id]) REFERENCES [tracks] ([id])
GO

ALTER TABLE [track_credits] ADD FOREIGN KEY ([artist_id]) REFERENCES [artists] ([id])
GO

ALTER TABLE [track_genres] ADD FOREIGN KEY ([track_id]) REFERENCES [tracks] ([id])
GO

ALTER TABLE [track_genres] ADD FOREIGN KEY ([genre_id]) REFERENCES [genres] ([id])
GO

ALTER TABLE [labels] ADD FOREIGN KEY ([parent_label_id]) REFERENCES [labels] ([id])
GO

ALTER TABLE [availability_windows] ADD FOREIGN KEY ([release_id]) REFERENCES [releases] ([id])
GO

ALTER TABLE [audio_files] ADD FOREIGN KEY ([track_id]) REFERENCES [tracks] ([id])
GO

ALTER TABLE [plan_prices] ADD FOREIGN KEY ([subscription_plan_id]) REFERENCES [subscription_plans] ([id])
GO

ALTER TABLE [subscriptions] ADD FOREIGN KEY ([owner_user_id]) REFERENCES [users] ([id])
GO

ALTER TABLE [subscriptions] ADD FOREIGN KEY ([subscription_plan_id]) REFERENCES [subscription_plans] ([id])
GO

ALTER TABLE [subscriptions] ADD FOREIGN KEY ([plan_price_id]) REFERENCES [plan_prices] ([id])
GO

ALTER TABLE [subscription_members] ADD FOREIGN KEY ([subscription_id]) REFERENCES [subscriptions] ([id])
GO

ALTER TABLE [subscription_members] ADD FOREIGN KEY ([user_id]) REFERENCES [users] ([id])
GO

ALTER TABLE [playlists] ADD FOREIGN KEY ([owner_user_id]) REFERENCES [users] ([id])
GO

ALTER TABLE [playlist_tracks] ADD FOREIGN KEY ([playlist_id]) REFERENCES [playlists] ([id])
GO

ALTER TABLE [playlist_tracks] ADD FOREIGN KEY ([track_id]) REFERENCES [tracks] ([id])
GO

ALTER TABLE [playlist_tracks] ADD FOREIGN KEY ([added_by]) REFERENCES [users] ([id])
GO

ALTER TABLE [playlist_collaborators] ADD FOREIGN KEY ([playlist_id]) REFERENCES [playlists] ([id])
GO

ALTER TABLE [playlist_collaborators] ADD FOREIGN KEY ([user_id]) REFERENCES [users] ([id])
GO

ALTER TABLE [follows] ADD FOREIGN KEY ([follower_id]) REFERENCES [users] ([id])
GO

ALTER TABLE [follows] ADD FOREIGN KEY ([followed_user_id]) REFERENCES [users] ([id])
GO

ALTER TABLE [follows] ADD FOREIGN KEY ([followed_artist_id]) REFERENCES [artists] ([id])
GO

ALTER TABLE [follows] ADD FOREIGN KEY ([followed_playlist_id]) REFERENCES [playlists] ([id])
GO

ALTER TABLE [library_saves] ADD FOREIGN KEY ([user_id]) REFERENCES [users] ([id])
GO

ALTER TABLE [library_saves] ADD FOREIGN KEY ([track_id]) REFERENCES [tracks] ([id])
GO

ALTER TABLE [library_saves] ADD FOREIGN KEY ([release_id]) REFERENCES [releases] ([id])
GO

ALTER TABLE [devices] ADD FOREIGN KEY ([user_id]) REFERENCES [users] ([id])
GO

ALTER TABLE [play_events] ADD FOREIGN KEY ([user_id]) REFERENCES [users] ([id])
GO

ALTER TABLE [play_events] ADD FOREIGN KEY ([track_id]) REFERENCES [tracks] ([id])
GO

ALTER TABLE [play_events] ADD FOREIGN KEY ([device_id]) REFERENCES [devices] ([id])
GO

ALTER TABLE [play_counts] ADD FOREIGN KEY ([track_id]) REFERENCES [tracks] ([id])
GO

ALTER TABLE [royalty_statements] ADD FOREIGN KEY ([royalty_pool_id]) REFERENCES [royalty_pools] ([id])
GO

ALTER TABLE [royalty_statements] ADD FOREIGN KEY ([label_id]) REFERENCES [labels] ([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 Music Streaming database schema?
users. It is referenced by 9 other tables: devices, follows, library_saves, play_events, playlist_collaborators and 4 more.
How is devices related to users?
devices.user_id references users.id, a many to one relationship. All 40 relationships in the schema are listed on this page.
Which table in the Music Streaming database schema has the most columns?
play_events, with 12 columns, followed by releases (12) and artists (10). The schema has 177 columns across 26 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.