Skip to content

Commit 709d4b3

Browse files
committed
Ensure role tables exist for SQLite
1 parent e41f34a commit 709d4b3

1 file changed

Lines changed: 41 additions & 0 deletions

File tree

website/MyWebApp/Program.cs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,7 @@
195195
UpgradePagesTable(db);
196196
UpgradeMediaItemsTable(db);
197197
UpgradeBlockTemplatesTable(db);
198+
UpgradeRolesTable(db);
198199
UpgradePermissionsTable(db);
199200
UpgradeLayoutHeader(db);
200201
}
@@ -512,6 +513,46 @@ FOREIGN KEY(BlockTemplateId) REFERENCES BlockTemplates(Id) ON DELETE CASCADE
512513
}
513514
}
514515

516+
static void UpgradeRolesTable(ApplicationDbContext db)
517+
{
518+
try
519+
{
520+
using var conn = db.Database.GetDbConnection();
521+
if (conn.State != System.Data.ConnectionState.Open)
522+
conn.Open();
523+
using var cmd = conn.CreateCommand();
524+
cmd.CommandText = "SELECT name FROM sqlite_master WHERE type='table' AND name='Roles'";
525+
var exists = cmd.ExecuteScalar() != null;
526+
if (!exists)
527+
{
528+
db.Database.ExecuteSqlRaw(@"CREATE TABLE Roles (
529+
Id INTEGER PRIMARY KEY AUTOINCREMENT,
530+
Name TEXT NOT NULL
531+
)");
532+
db.Database.ExecuteSqlRaw("CREATE UNIQUE INDEX IX_Roles_Name ON Roles(Name)");
533+
db.Database.ExecuteSqlRaw(@"INSERT INTO Roles (Id, Name) VALUES
534+
(1, 'Admin'), (2, 'User'), (3, 'Moderator')");
535+
}
536+
537+
cmd.CommandText = "SELECT name FROM sqlite_master WHERE type='table' AND name='UserRoles'";
538+
exists = cmd.ExecuteScalar() != null;
539+
if (!exists)
540+
{
541+
db.Database.ExecuteSqlRaw(@"CREATE TABLE UserRoles (
542+
SiteUserId INTEGER NOT NULL,
543+
RoleId INTEGER NOT NULL,
544+
PRIMARY KEY(SiteUserId, RoleId),
545+
FOREIGN KEY(SiteUserId) REFERENCES SiteUsers(Id) ON DELETE CASCADE,
546+
FOREIGN KEY(RoleId) REFERENCES Roles(Id) ON DELETE CASCADE
547+
)");
548+
}
549+
}
550+
catch (Exception ex)
551+
{
552+
Console.Error.WriteLine($"Schema upgrade failed: {ex.Message}");
553+
}
554+
}
555+
515556
static void UpgradePermissionsTable(ApplicationDbContext db)
516557
{
517558
try

0 commit comments

Comments
 (0)