Skip to content

Latest commit

 

History

History
244 lines (205 loc) · 14.4 KB

database-schema.md

File metadata and controls

244 lines (205 loc) · 14.4 KB

Database Schema

Overview

AddictedProxy uses PostgreSQL as its primary database, accessed via Entity Framework Core 10 with the Npgsql provider. Persistent entities inherit from BaseEntity, which provides CreatedAt and UpdatedAt provenance timestamps.

Schema changes are managed via EF Core migrations (located in AddictedProxy.Database/Migrations/), which are auto-applied on application startup via dbContext.Database.MigrateAsync().

Tables with an UpdatedAt column are expected to have a PostgreSQL BEFORE UPDATE trigger that calls updated_set_now() and writes UpdatedAt in UTC. New persisted models should keep inheriting from BaseEntity, and the EF migration that creates the table should also create and drop that trigger explicitly.

One-time data migrations (not schema changes) are handled by the OneTimeMigration framework (see Background Jobs).

Entity Relationship Diagram

┌─────────────────────────────────────────┐
│                TvShow                   │
├─────────────────────────────────────────┤
│ Id (PK, long)                           │
│ UniqueId (Guid, unique, default uuidv7) │
│ ExternalId (long, legacy)               │  ◄── Legacy Addic7ed show ID (kept for compatibility)
│ Name (string)                           │
│ TmdbId (int?)                           │  ◄── The Movie Database ID
│ TvdbId (int?, indexed)                  │  ◄── TheTVDB ID
│ Type (ShowType enum)                    │  ◄── Show | Movie
│ Source (DataSource enum)                │  ◄── Where the show was first discovered
│ IsCompleted (bool)                      │
│ Priority (int, default 0)              │
│ LastUpdated (DateTime)                  │
│ LastSeasonRefreshed (DateTime?)         │
│ Discovered (DateTime)                   │
│ CreatedAt / UpdatedAt (BaseEntity)      │
├─────────────────────────────────────────┤
│ ◄──── 1:M ────► Seasons[]              │
│ ◄──── 1:M ────► Episodes[]             │
└─────────────────────────────────────────┘
          │                    │
          │ 1:M                │ 1:M
          ▼                    ▼
┌──────────────────┐  ┌──────────────────────────────────────┐
│     Season       │  │             Episode                   │
├──────────────────┤  ├──────────────────────────────────────┤
│ Id (PK, long)    │  │ Id (PK, long)                        │
│ TvShowId (FK)    │  │ TvShowId (FK)                        │
│ Number (int)     │  │ Season (int)                         │
│ LastRefreshed    │  │ Number (int)                         │
│ (DateTime?)      │  │ Title (string)                       │
│ CreatedAt /      │  │ Discovered (DateTime)                │
│ UpdatedAt        │  │ CreatedAt / UpdatedAt                │
├──────────────────┤  ├──────────────────────────────────────┤
│ Unique:          │  │ Unique: (TvShowId, Season, Number)   │
│ (TvShowId,Number)│  │ ◄──── 1:M ────► Subtitles[]         │
└──────────────────┘  └──────────────────────────────────────┘
                                        │
                                        │ 1:M
                                        ▼
                      ┌──────────────────────────────────────────┐
                      │              Subtitle                     │
                      ├──────────────────────────────────────────┤
                      │ Id (PK, long)                             │
                      │ UniqueId (Guid, unique, default uuidv7)   │
                      │ EpisodeId (FK to Episode)                 │
                      │ Language (string)                         │
                      │ LanguageIsoCode (VARCHAR(7), nullable)    │
                      │ Scene (string)                            │  ◄── Release group/scene name
                      │ Version (int)                             │  ◄── Subtitle version number
                      │ Completed (bool)                          │
                      │ CompletionPct (double)                    │
                      │ HearingImpaired (bool)                    │
                      │ Corrected (bool)                          │
                      │ HD (bool, legacy/obsolete)                │  ◄── Kept until BackportHdToQualitiesMigration has run
                      │ Qualities (VideoQuality flags bitmask)    │  ◄── Q720P/Q1080P/Q2160P etc.
                      │ Release (string?, nullable)               │  ◄── Full release name (SuperSubtitles; null for Addic7ed)
                      │ DownloadUri (Uri, unique)                 │  ◄── Original download URL
                      │ DownloadCount (long)                      │
                      │ StoragePath (string?, nullable)           │  ◄── Path in S3/storage
                      │ StoredAt (DateTime?, nullable)            │
                      │ Source (DataSource enum)                  │  ◄── Which provider this came from
                      │ ExternalId (string?, nullable)            │  ◄── Provider-specific subtitle ID
                      │ Discovered (DateTime)                     │
                      │ CreatedAt / UpdatedAt (BaseEntity)        │
                      ├──────────────────────────────────────────┤
                      │ Index: (DownloadUri) unique               │
                      │ Index: (Source, ExternalId) unique         │
                      │ Index: (EpisodeId, Language, Version)     │
                      │ Index: (UniqueId) unique                  │
                      └──────────────────────────────────────────┘

Multi-Provider Entities

The schema also includes provider mapping tables used by the merge pipeline:

  • ShowExternalId: maps provider (Source, ExternalId) values to a single TvShow (Unique: (TvShowId, Source) and Unique: (Source, ExternalId)).
  • EpisodeExternalId: maps provider (Source, ExternalId) values to a single Episode (Unique: (EpisodeId, Source) and Unique: (Source, ExternalId)).
  • SeasonPackSubtitle: stores season-pack subtitles (provider metadata + optional storage path), unique by (Source, ExternalId) where ExternalId is a numeric (long) provider ID. Includes DownloadCount (long) for download tracking, nullable DeletedAt for soft deletion of corrupt packs, and an optional SeasonId FK to Season (backfilled via one-time migration, resolved during ingestion). Default EF queries exclude rows where DeletedAt is not null, and writes use an EF SaveChangesInterceptor to translate deletes into soft deletes.

Enums

DataSource

Identifies the upstream provider that contributed a show or subtitle.

public enum DataSource
{
    Addic7ed,
    SuperSubtitles
}

ShowType

public enum ShowType
{
    Show,   // TV series
    Movie   // Film
}

MigrationState (OneTimeMigrationRelease)

public enum MigrationState
{
    Success,
    Running,
    Fail
}

Other Entities

AddictedUserCredentials

Stores Addic7ed account credentials for authenticated API access. Multiple accounts are rotated to distribute rate limiting.

┌──────────────────────────────────────┐
│     AddictedUserCredentials          │
├──────────────────────────────────────┤
│ Id (PK, int)                         │
│ Cookie (string, unique)              │  ◄── Session cookie for Addic7ed
│ Usage (int)                          │  ◄── Query usage counter
│ DownloadUsage (int)                  │  ◄── Download usage counter
│ LastUsage (DateTime?)                │
│ DownloadExceededDate (DateTime?)     │  ◄── When download limit was hit
│ CreatedAt / UpdatedAt (BaseEntity)   │
└──────────────────────────────────────┘

OneTimeMigrationRelease

Tracks one-time data migration execution status. Prevents duplicate/concurrent migrations.

┌──────────────────────────────────────┐
│     OneTimeMigrationRelease          │
├──────────────────────────────────────┤
│ Id (Guid, PK)                        │
│ MigrationType (string)               │  ◄── Format: "YYYY-M-D_ClassName"
│ State (MigrationState enum)          │
│ CreatedAt / UpdatedAt (BaseEntity)   │
├──────────────────────────────────────┤
│ Unique: (MigrationType, State)       │
└──────────────────────────────────────┘

Repository Interfaces

ITvShowRepository

FindAsync(name)                              // Full-text search by name
GetByIdAsync(id)                             // Get by primary key
GetByGuidAsync(guid)                         // Get by UniqueId
GetByTvdbIdAsync(tvdbId)                     // Get by TheTVDB ID
GetAllAsync()                                // All shows
GetShowsByTmdbIdAsync(tmdbIds)               // Get by TMDB ID(s)
GetShowWithoutTmdbIdAsync()                  // Shows missing TMDB mapping
GetShowsWithoutTvdbIdWithTmdbIdAsync()       // Shows with TMDB but missing TVDB
GetCompletedShows(isCompleted)               // Shows filtered by completion state
GetDuplicateTvShowByTmdbIdAsync()            // Find duplicate TMDB mappings
UpsertRefreshedShowsAsync(shows)             // Bulk upsert shows
InsertShowAsync(show)                        // Insert a single show
UpdateShowAsync(show)                        // Single show update
BulkSaveChangesAsync()                       // Batch save

IEpisodeRepository

UpsertEpisodes(episodes)                     // Bulk upsert episodes with subtitles + EpisodeExternalIds (EFCore.BulkExtensions BulkMergeAsync with IncludeGraph)
GetEpisodeUntrackedAsync(showId, season, ep) // Get episode (no change tracking)
GetSeasonsHavingEpisodesAsync(tvShowIds)     // Set of (TvShowId, Season) pairs that have at least one episode (single AsNoTracking query)
GetSeasonEpisodesAsync(showId, season)       // All episodes in a season
GetSeasonEpisodesByLangUntrackedAsync(...)   // Episodes filtered by language

⚠️ Raw SQL: EpisodeExternalIdRepository uses a raw SQL INSERT ... ON CONFLICT ("Source", "ExternalId") DO NOTHING statement that references EpisodeExternalId columns by name. When adding, removing, or renaming columns on that entity, you must update the SQL manually — the compiler will not catch mismatches.

ISeasonRepository

InsertNewSeasonsAsync(showId, seasons)        // Insert new seasons
GetSeasonForShowAsync(showId, seasonNumber)   // Get specific season
GetSeasonsForShowAsync(showId)                // All seasons for show
GetSeasonIdLookupAsync(showIds)               // (TvShowId, Number) → SeasonId lookup map
SaveChangesAsync()                            // Save changes
UpdateLastRefreshedFromIdAsync(id, date)      // Update refresh timestamp
DeleteEmptySeasonsForShowAsync(showId)        // Delete seasons of a show that have neither episodes nor season packs

ISubtitleRepository

GetSubtitleByIdAsync(id)                                  // Get by PK
GetSubtitleByGuidAsync(guid, withEpisode, withShow)       // Get by UniqueId (optionally including Episode/TvShow)
SaveChangeAsync()                                         // Save changes
IncrementDownloadCountAsync(subtitle)                     // Atomic counter increment
TagForRemoval(subtitle)                                   // Mark for deletion

ISeasonPackSubtitleRepository

GetByShowAndSeasonAsync(tvShowId, season)                 // All packs for a show + season
GetBySourceAndExternalIdAsync(source, externalId)         // Lookup by provider + ID
GetByUniqueIdAsync(uniqueId)                              // Lookup by UniqueId (for download)
GetUnstoredByExternalIdsAsync(source, externalIds)        // Packs from a provider with no StoragePath yet
BulkUpsertAsync(seasonPacks)                              // Bulk upsert (ignores DownloadCount on update)
IncrementDownloadCountAsync(seasonPackSubtitle)           // Atomic counter increment
SoftDeleteAsync(seasonPackSubtitle)                       // Set DeletedAt (soft delete of corrupt packs)
SaveChangeAsync()                                         // Save changes

Database Configuration

  • Connection String: Configured via appsettings.json or environment variables
  • UUID Generation: uuidv7() PostgreSQL function for sortable unique IDs
  • Collation: Case-insensitive collation for text search
  • Migrations: Auto-applied at startup via MigrateAsync()
  • Transactions: Managed via ITransactionManager<EntityContext> for multi-step operations