divan/RMuseum/DbContext/RMuseumDbContext.cs
Anas Rashid e8f2306422 Rename Ganjoor -> Diwan throughout the code
Projects (GanjooRazor -> DiwanRazor, GanjoorService.sln -> DiwanService.sln), files,
folders, classes, namespaces, settings, API routes (/api/diwan) and DB tables (Diwan*).
External addresses (ganjoor.net, github.com/ganjoor) unchanged. Migrations renamed
consistently (no pending model changes); requires a fresh database.
Upstream RUNNING_LOCALLY/SEMANTIC_SEARCH docs archived unmodified under docs/.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 23:49:01 +02:00

758 lines
24 KiB
C#

using Microsoft.EntityFrameworkCore;
using RMuseum.Models.Artifact;
using RMuseum.Models.Bookmark;
using RMuseum.Models.DiwanAudio;
using RMuseum.Models.UploadSession;
using RMuseum.Models.DiwanIntegration;
using RMuseum.Models.ImportJob;
using RMuseum.Models.Note;
using RSecurityBackend.DbContext;
using RSecurityBackend.Models.Auth.Db;
using System;
using RMuseum.Models.Diwan;
using RMuseum.Models.Diwan.SemanticSearch;
using RMuseum.Models.MusicCatalogue;
using RMuseum.Models.Accounting;
using Microsoft.Extensions.Configuration;
using System.IO;
using RMuseum.Models.FAQ;
using RMuseum.Models.PDFLibrary;
using RMuseum.Models.ExternalFTPUpload;
namespace RMuseum.DbContext
{
/// <summary>
/// Museum Database Context
/// </summary>
public class RMuseumDbContext : RSecurityDbContext<RAppUser, RAppRole, Guid>
{
public RMuseumDbContext(DbContextOptions<RMuseumDbContext> options) : base(options)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").AddEnvironmentVariables() // diwan: honour env overrides (Docker)
.Build();
if (bool.Parse(configuration["DatabaseMigrate"]))
{
Database.SetCommandTimeout(18000);//set time out for migration to 5 hours
Database.Migrate();
}
}
/// <summary>
///
/// </summary>
/// <param name="builder"></param>
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<RArtifactMasterRecord>()
.HasIndex(m => m.FriendlyUrl)
.IsUnique();
builder.Entity<RArtifactItemRecord>()
.HasIndex(i => new { i.RArtifactMasterRecordId, i.FriendlyUrl })
.IsUnique();
builder.Entity<RArtifactItemRecord>()
.HasIndex(i => new { i.RArtifactMasterRecordId, i.Order })
.IsUnique();
builder.Entity<RTag>()
.HasIndex(t => t.FriendlyUrl);
builder.Entity<RTagValue>()
.HasIndex(t => t.FriendlyUrl);
builder.Entity<Recitation>()
.HasIndex(p => p.DiwanPostId);
builder.Entity<DiwanCat>()
.HasIndex(c => c.FullUrl);
builder.Entity<DiwanPoem>()
.HasIndex(c => c.FullUrl);
builder.Entity<DiwanPage>()
.HasIndex(c => c.FullUrl);
builder.Entity<DiwanSinger>()
.HasIndex(c => c.Name);
builder.Entity<DiwanTrack>()
.HasIndex(c => c.Name);
builder.Entity<DiwanComment>()
.HasIndex(c => c.CommentDate);
builder.Entity<ImportJob>()
.Property(c => c.ProgressPercent)
.HasColumnType("decimal(18,2)");
builder.Entity<DiwanComment>()
.HasIndex(c => c.Status);
builder.Entity<DiwanPoem>()
.HasIndex(c => c.Id);
builder.Entity<Recitation>()
.HasIndex(c => c.DiwanAudioId);
builder.Entity<Recitation>()
.HasIndex(c => new { c.ReviewStatus, c.DiwanPostId });
builder.Entity<RArtifactMasterRecord>()
.HasIndex(c => c.LastModified);
builder.Entity<DiwanPoet>()
.HasIndex(c => new { c.Published, c.Id })
.IncludeProperties(c => new { c.Name, c.Nickname, c.RImageId });
builder.Entity<DiwanCat>()
.HasIndex(c => new { c.ParentId, c.PoetId })
.IncludeProperties(c => c.Id);
builder.Entity<PoemMusicTrack>()
.HasIndex(c => new { c.Approved, c.Rejected });
builder.Entity<RArtifactMasterRecord>()
.HasIndex(c => new { c.CoverItemIndex, c.Status });
builder.Entity<DiwanLanguage>()
.HasIndex(m => m.Name)
.IsUnique();
// DiwanPersonRelation has two required FKs to the same table (DiwanRelatedPerson) -
// left at their EF Core default (Cascade, since both are required/non-nullable), SQL
// Server refuses to create the second FK with "may cause cycles or multiple cascade
// paths". Restricting one side (Person2) is enough to break the ambiguity; deleting a
// person that's still referenced by a relation should be prevented at the application
// level anyway (via a "still has family tree entries" check), not silently cascaded.
builder.Entity<DiwanPersonRelation>()
.HasOne(r => r.Person1)
.WithMany()
.HasForeignKey(r => r.Person1Id)
.OnDelete(DeleteBehavior.Restrict);
builder.Entity<DiwanPersonRelation>()
.HasOne(r => r.Person2)
.WithMany()
.HasForeignKey(r => r.Person2Id)
.OnDelete(DeleteBehavior.Restrict);
// same two-required-FKs-to-the-same-table situation as DiwanPersonRelation above
builder.Entity<DiwanPersonAffiliation>()
.HasOne(a => a.Person1)
.WithMany()
.HasForeignKey(a => a.Person1Id)
.OnDelete(DeleteBehavior.Restrict);
builder.Entity<DiwanPersonAffiliation>()
.HasOne(a => a.Person2)
.WithMany()
.HasForeignKey(a => a.Person2Id)
.OnDelete(DeleteBehavior.Restrict);
// same two-required-FKs-to-the-same-table situation as DiwanPersonRelation above, plus
// a third optional FK to DiwanPersonRelations itself (ExistingRelationId) - also
// restricted, since a relation that still has a pending suggestion against it should be
// resolved (or the suggestion rejected) before it can be deleted directly, not silently
// orphan the suggestion
builder.Entity<DiwanPersonRelationEditSuggestion>()
.HasOne(s => s.Person1)
.WithMany()
.HasForeignKey(s => s.Person1Id)
.OnDelete(DeleteBehavior.Restrict);
builder.Entity<DiwanPersonRelationEditSuggestion>()
.HasOne(s => s.Person2)
.WithMany()
.HasForeignKey(s => s.Person2Id)
.OnDelete(DeleteBehavior.Restrict);
builder.Entity<DiwanPersonRelationEditSuggestion>()
.HasOne(s => s.ExistingRelation)
.WithMany()
.HasForeignKey(s => s.ExistingRelationId)
.OnDelete(DeleteBehavior.Restrict);
// same Restrict treatment as ExistingRelationId above, but for Kind == Affiliation
// suggestions targeting a DiwanPersonAffiliation instead
builder.Entity<DiwanPersonRelationEditSuggestion>()
.HasOne(s => s.ExistingAffiliation)
.WithMany()
.HasForeignKey(s => s.ExistingAffiliationId)
.OnDelete(DeleteBehavior.Restrict);
builder.Entity<DiwanUserBookmark>()
.HasIndex(b => new { b.UserId, b.PoemId, b.CoupletIndex });
builder.Entity<DiwanVerseNumber>()
.HasIndex(n => new { n.NumberingId, n.PoemId, n.CoupletIndex })
.IsUnique();
builder.Entity<DiwanVerseNumber>()
.HasIndex(n => new { n.PoemId, n.CoupletIndex });
builder.Entity<DiwanVerse>()
.HasIndex(v => v.PoemId);//the next statement causes a drop index in the migration which this line prevents it
builder.Entity<DiwanVerse>()
.HasIndex(v => new { v.PoemId, v.CoupletIndex });
builder.Entity<DiwanCachedRelatedPoem>()
.HasIndex(c => new { c.PoemId });
builder.Entity<DiwanCachedRelatedPoem>()
.HasIndex(c => new { c.FullUrl });
builder.Entity<DiwanDonation>()
.Property(c => c.Amount)
.HasColumnType("decimal(18,2)");
builder.Entity<DiwanDonation>()
.Property(c => c.Remaining)
.HasColumnType("decimal(18,2)");
builder.Entity<DiwanExpense>()
.Property(c => c.Amount)
.HasColumnType("decimal(18,2)");
builder.Entity<DonationExpenditure>()
.Property(c => c.Amount)
.HasColumnType("decimal(18,2)");
builder.Entity<DiwanGeoLocation>()
.Property(c => c.Latitude)
.HasColumnType("decimal(12,9)");
builder.Entity<DiwanGeoLocation>()
.Property(c => c.Longitude)
.HasColumnType("decimal(12,9)");
builder.Entity<RecitationUserUpVote>()
.HasIndex(v => new { v.RecitationId, v.UserId })
.IsUnique();
builder.Entity<DiwanUserPoemVisit>()
.HasIndex(v => v.UserId);
builder.Entity<DiwanUserPoemVisit>()
.HasIndex(v => new { v.UserId, v.PoemId });
builder.Entity<DiwanPoemSection>()
.HasIndex(v => new { v.PoemId, v.Index });
builder.Entity<DiwanPoemSection>()
.HasIndex(v => new { v.RhymeLetters });
builder.Entity<DiwanPoemSection>()
.HasIndex(v => new { v.DiwanMetreId, v.RhymeLetters });
builder.Entity<DiwanPoemSection>()
.HasIndex(v => new { v.DiwanMetreId, v.RhymeLetters, v.Id});
builder.Entity<DiwanPoemSection>()
.HasIndex(v => new { v.DiwanMetreId, v.RhymeLetters, v.SectionType });
builder.Entity<DiwanCachedRelatedSection>()
.HasIndex(v => new { v.PoemId, v.SectionIndex });
builder.Entity<CategoryWordCount>()
.HasIndex(v => new { v.CatId, v.Word })
.IsUnique();
builder.Entity<CategoryWordCountSummary>()
.HasIndex(v => new { v.CatId })
.IsUnique();
builder.Entity<DiwanVerse>()
.Property(e => e.CoupletSummary)
.HasMaxLength(4000);
builder.Entity<DiwanPoem>()
.Property(e => e.Title)
.HasMaxLength(1500);
builder.Entity<DiwanPoem>()
.Property(e => e.FullTitle)
.HasMaxLength(1500);
builder.Entity<DiwanPoem>()
.Property(e => e.UrlSlug)
.HasMaxLength(32);
builder.Entity<DiwanPoem>()
.Property(e => e.RhymeLetters)
.HasMaxLength(64);
builder.Entity<DiwanPoem>()
.Property(e => e.SourceName)
.HasMaxLength(64);
builder.Entity<DiwanPoem>()
.Property(e => e.SourceUrlSlug)
.HasMaxLength(16);
builder.Entity<DiwanPoem>()
.Property(e => e.OldTag)
.HasMaxLength(16);
builder.Entity<DiwanPoem>()
.Property(e => e.OldTagPageUrl)
.HasMaxLength(32);
builder.Entity<DiwanPoem>()
.Property(e => e.Language)
.HasMaxLength(8);
builder.Entity<DiwanPoem>()
.Property(e => e.PoemSummary)
.HasMaxLength(3000);
builder.Entity<DiwanCommentReaction>()
.HasIndex(i => new { i.DiwanCommentId, i.UserId })
.IsUnique();
builder.Entity<DiwanCommentReaction>()
.HasIndex(i => new { i.PoemId, i.UserId });
builder.Entity<DiwanComment>()
.HasIndex(i => new { i.PoemId, i.SortKey });
builder.Entity<DiwanComment>()
.HasIndex(i => new { i.PoemId, i.CommentDate });
}
/// <summary>
/// Picture Files
/// </summary>
public DbSet<RPictureFile> PictureFiles { get; set; }
/// <summary>
/// Item Attributes
/// </summary>
public DbSet<RTag> Tags { get; set; }
/// <summary>
/// Artifacts
/// </summary>
public DbSet<RArtifactMasterRecord> Artifacts { get; set; }
/// <summary>
/// Items
/// </summary>
public DbSet<RArtifactItemRecord> Items { get; set; }
/// <summary>
/// Import Jobs
/// </summary>
public DbSet<ImportJob> ImportJobs { get; set; }
/// <summary>
/// Tags
/// </summary>
public DbSet<RTagValue> TagValues { get; set; }
/// <summary>
/// User Bookmarks
/// </summary>
public DbSet<RUserBookmark> UserBookmarks { get; set; }
/// <summary>
/// User Notes
/// </summary>
public DbSet<RUserNote> UserNotes { get; set; }
/// <summary>
/// Diwan Links
/// </summary>
public DbSet<DiwanLink> DiwanLinks { get; set; }
/// <summary>
/// Pinterest Links
/// </summary>
public DbSet<PinterestLink> PinterestLinks { get; set; }
/// <summary>
/// Diwan Audio Files
/// </summary>
public DbSet<Recitation> Recitations { get; set; }
/// <summary>
/// Upload Sessions
/// </summary>
public DbSet<UploadSession> UploadSessions { get; set; }
/// <summary>
/// Uploaded files
/// </summary>
public DbSet<UploadSessionFile> UploadedFiles { get; set; }
/// <summary>
/// User Recitation Profiles
/// </summary>
public DbSet<UserRecitationProfile> UserRecitationProfiles { get; set; }
/// <summary>
/// Diwan Poets
/// </summary>
public DbSet<DiwanPoet> DiwanPoets { get; set; }
/// <summary>
/// Diwan Categories
/// </summary>
public DbSet<DiwanCat> DiwanCategories { get; set; }
/// <summary>
/// Diwan Poems
/// </summary>
public DbSet<DiwanPoem> DiwanPoems { get; set; }
/// <summary>
/// Semantic search query log — see SemanticSearchQueryLog for what is (and deliberately
/// isn't) recorded
/// </summary>
public DbSet<SemanticSearchQueryLog> SemanticSearchQueryLogs { get; set; }
/// <summary>
/// Diwan Verses
/// </summary>
public DbSet<DiwanVerse> DiwanVerses { get; set; }
/// <summary>
/// Narration Publishing Tracker
/// </summary>
public DbSet<RecitationPublishingTracker> RecitationPublishingTrackers { get; set; }
/// <summary>
/// Diwan Pages
/// </summary>
public DbSet<DiwanPage> DiwanPages { get; set; }
/// <summary>
/// Diwan Metres
/// </summary>
public DbSet<DiwanMetre> DiwanMetres { get; set; }
/// <summary>
/// singers
/// </summary>
public DbSet<DiwanSinger> DiwanSingers { get; set; }
/// <summary>
/// music tracks
/// </summary>
public DbSet<DiwanTrack> DiwanMusicCatalogueTracks { get; set; }
/// <summary>
/// golha tracks
/// </summary>
public DbSet<GolhaTrack> GolhaTracks { get; set; }
/// <summary>
/// GolhaCollection
/// </summary>
public DbSet<GolhaCollection> GolhaCollections { get; set; }
/// <summary>
/// GolhaPrograms
/// </summary>
public DbSet<GolhaProgram> GolhaPrograms { get; set; }
/// <summary>
/// PoemMusicTracks
/// </summary>
public DbSet<PoemMusicTrack> DiwanPoemMusicTracks { get; set; }
/// <summary>
/// Diwan Comments
/// </summary>
public DbSet<DiwanComment> DiwanComments { get; set; }
/// <summary>
/// Diwan Reported Comments
/// </summary>
public DbSet<DiwanCommentAbuseReport> DiwanReportedComments { get; set; }
/// <summary>
/// Diwan Page Snapshots
/// </summary>
public DbSet<DiwanPageSnapshot> DiwanPageSnapshots { get; set; }
/// <summary>
/// Diwan Site Bannaers
/// </summary>
public DbSet<DiwanSiteBanner> DiwanSiteBanners { get; set; }
/// <summary>
/// Diwan Health Check Errors
/// </summary>
public DbSet<DiwanHealthCheckError> DiwanHealthCheckErrors { get; set; }
/// <summary>
/// donations
/// </summary>
public DbSet<DiwanDonation> DiwanDonations { get; set; }
/// <summary>
/// expenses
/// </summary>
public DbSet<DiwanExpense> DiwanExpenses { get; set; }
/// <summary>
/// donation expenditures
/// </summary>
public DbSet<DonationExpenditure> DonationExpenditure { get; set; }
/// <summary>
/// poem corrections
/// </summary>
public DbSet<DiwanPoemCorrection> DiwanPoemCorrections { get; set; }
/// <summary>
/// languages for translation
/// </summary>
public DbSet<DiwanLanguage> DiwanLanguages { get; set; }
/// <summary>
/// diwan bookmarks
/// </summary>
public DbSet<DiwanUserBookmark> DiwanUserBookmarks { get; set; }
/// <summary>
/// diwan numbering schemas
/// </summary>
public DbSet<DiwanNumbering> DiwanNumberings { get; set; }
/// <summary>
/// diwan verse numbers
/// </summary>
public DbSet<DiwanVerseNumber> DiwanVerseNumbers { get; set; }
/// <summary>
/// diwan half centuries
/// </summary>
public DbSet<DiwanCentury> DiwanCenturies { get; set; }
/// <summary>
/// diwan cities
/// </summary>
public DbSet<DiwanGeoLocation> DiwanGeoLocations { get; set; }
/// <summary>
/// related poems to each poem (having same rhyme letters and prosody metre)
/// </summary>
public DbSet<DiwanCachedRelatedPoem> DiwanCachedRelatedPoems { get; set; }
/// <summary>
/// Reported User Notes
/// </summary>
public DbSet<RUserNoteAbuseReport> ReportedUserNotes { get; set; }
/// <summary>
/// recitation error reports
/// </summary>
public DbSet<RecitationErrorReport> RecitationErrorReports { get; set; }
/// <summary>
/// recitation user up votes
/// </summary>
public DbSet<RecitationUserUpVote> RecitationUserUpVotes { get; set; }
/// <summary>
/// recitation approved mistakes
/// </summary>
public DbSet<RecitationApprovedMistake> RecitationApprovedMistakes { get; set; }
/// <summary>
/// probable metres
/// </summary>
public DbSet<DiwanPoemProbableMetre> DiwanPoemProbableMetres { get; set; }
/// <summary>
/// diwan user history track items (stored by his or her choice)
/// </summary>
public DbSet<DiwanUserPoemVisit> DiwanUserPoemVisits { get; set; }
/// <summary>
/// suggested spec line for poets
/// </summary>
public DbSet<DiwanPoetSuggestedSpecLine> DiwanPoetSuggestedSpecLines { get; set; }
/// <summary>
/// suggested pictures for poets
/// </summary>
public DbSet<DiwanPoetSuggestedPicture> DiwanPoetSuggestedPictures { get; set; }
/// <summary>
/// faq categories
/// </summary>
public DbSet<FAQCategory> FAQCategories { get; set; }
/// <summary>
/// faq items
/// </summary>
public DbSet<FAQItem> FAQItems { get; set; }
/// <summary>
/// Temporary Model contianing duplicated poems information
/// </summary>
public DbSet<DiwanDuplicate> DiwanDuplicates { get; set; }
/// <summary>
/// poem sections
/// </summary>
public DbSet<DiwanPoemSection> DiwanPoemSections { get; set; }
/// <summary>
/// related sections to each section (having same rhyme letters and prosody metre)
/// </summary>
public DbSet<DiwanCachedRelatedSection> DiwanCachedRelatedSections { get; set; }
/// <summary>
/// section correctons
/// </summary>
public DbSet<DiwanPoemSectionCorrection> DiwanPoemSectionCorrections { get; set; }
/// <summary>
/// Updating related sections logs
/// </summary>
public DbSet<UpdatingRelSectsLog> UpdatingRelSectsLogs{ get; set; }
/// <summary>
/// PoemGeoDateTags
/// </summary>
public DbSet<PoemGeoDateTag> PoemGeoDateTags { get; set; }
/// <summary>
/// People tags
/// </summary>
public DbSet<DiwanRelatedPerson> DiwanRelatedPersons { get; set; }
/// <summary>
/// approved kinship edges between people (family tree) - see DiwanPersonRelation
/// </summary>
public DbSet<DiwanPersonRelation> DiwanPersonRelations { get; set; }
/// <summary>
/// approved non-family ties between people (e.g. minister-to-king) - see DiwanPersonAffiliation
/// </summary>
public DbSet<DiwanPersonAffiliation> DiwanPersonAffiliations { get; set; }
/// <summary>
/// pending/reviewed suggested edits to an already-approved DiwanRelatedPerson's own fields -
/// see DiwanPersonEditSuggestion
/// </summary>
public DbSet<DiwanPersonEditSuggestion> DiwanPersonEditSuggestions { get; set; }
/// <summary>
/// pending/reviewed suggested additions, changes or removals of a kinship edge between two
/// already-approved people - see DiwanPersonRelationEditSuggestion
/// </summary>
public DbSet<DiwanPersonRelationEditSuggestion> DiwanPersonRelationEditSuggestions { get; set; }
/// <summary>
/// Books (PDF Library)
/// </summary>
public DbSet<Book> Books { get; set; }
/// <summary>
/// Authurs
/// </summary>
public DbSet<Author> Authors { get; set; }
/// <summary>
/// Multi Volume PDF Collections
/// </summary>
public DbSet<MultiVolumePDFCollection> MultiVolumePDFCollections { get; set; }
/// <summary>
/// PDF Books
/// </summary>
public DbSet<PDFBook> PDFBooks { get; set; }
/// <summary>
/// PDF Pages
/// </summary>
public DbSet<PDFPage> PDFPages { get; set; }
/// <summary>
/// PDF Sources
/// </summary>
public DbSet<PDFSource> PDFSources { get; set; }
/// <summary>
/// Queued FTP Uploads
/// </summary>
public DbSet<QueuedFTPUpload> QueuedFTPUploads { get; set; }
/// <summary>
/// PDF Diwan Links
/// </summary>
public DbSet<PDFDiwanLink> PDFDiwanLinks { get; set; }
/// <summary>
/// OCR Queue Items
/// </summary>
public DbSet<OCRQueue> OCRQueuedItems { get; set; }
/// <summary>
/// PDF Download Queue
/// </summary>
public DbSet<QueuedPDFBook> QueuedPDFBooks { get; set; }
/// <summary>
/// Related Poems
/// </summary>
public DbSet<DiwanQuotedPoem> DiwanQuotedPoems { get; set; }
/// <summary>
/// discover quoted q items
/// </summary>
public DbSet<DiscoverQuotedQueueItem> DiscoverQuotedQueueItems { get; set; }
/// <summary>
/// paper sources
/// </summary>
public DbSet<DiwanPaperSource> DiwanPaperSources { get; set; }
/// <summary>
/// digital sources
/// </summary>
public DbSet<DigitalSource> DigitalSources { get; set; }
/// <summary>
/// Category Word Counts
/// </summary>
public DbSet<CategoryWordCount> CategoryWordCounts { get; set; }
/// <summary>
/// Category Word Count Summaries
/// </summary>
public DbSet<CategoryWordCountSummary> CategoryWordCountSummaries { get; set; }
/// <summary>
/// diwan cat corrections
/// </summary>
public DbSet<DiwanCatCorrection> DiwanCatCorrections { get; set; }
/// <summary>
/// comment reactions
/// </summary>
public DbSet<DiwanCommentReaction> DiwanCommentReactions { get; set; }
}
}