Configurable data directory for Docker + auto-add ExpiresAt column for existing databases
This commit is contained in:
+32
-2
@@ -4,8 +4,12 @@ using NoticeBoard.Data;
|
|||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
|
||||||
// SQLite database in app directory
|
// SQLite database. Defaults to the app's own directory (unchanged behaviour for IIS).
|
||||||
var dbPath = Path.Combine(builder.Environment.ContentRootPath, "noticeboard.db");
|
// Set the "DataDirectory" setting (env var DataDirectory=... in Docker) to store the
|
||||||
|
// database elsewhere — used by the Docker image so the DB lives on a mounted volume.
|
||||||
|
var dataDir = builder.Configuration["DataDirectory"] ?? builder.Environment.ContentRootPath;
|
||||||
|
Directory.CreateDirectory(dataDir);
|
||||||
|
var dbPath = Path.Combine(dataDir, "noticeboard.db");
|
||||||
builder.Services.AddDbContext<AppDbContext>(options =>
|
builder.Services.AddDbContext<AppDbContext>(options =>
|
||||||
options.UseSqlite($"Data Source={dbPath}"));
|
options.UseSqlite($"Data Source={dbPath}"));
|
||||||
|
|
||||||
@@ -29,6 +33,32 @@ using (var scope = app.Services.CreateScope())
|
|||||||
{
|
{
|
||||||
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||||
db.Database.EnsureCreated();
|
db.Database.EnsureCreated();
|
||||||
|
|
||||||
|
// This project doesn't use formal EF Core migrations — EnsureCreated only builds a
|
||||||
|
// brand-new database from the current model. For an existing Slides table (from before
|
||||||
|
// the ExpiresAt column existed), add it here so upgrades don't require a manual step.
|
||||||
|
var connection = db.Database.GetDbConnection();
|
||||||
|
await connection.OpenAsync();
|
||||||
|
var hasExpiresAt = false;
|
||||||
|
await using (var checkCmd = connection.CreateCommand())
|
||||||
|
{
|
||||||
|
checkCmd.CommandText = "PRAGMA table_info(Slides);";
|
||||||
|
await using var reader = await checkCmd.ExecuteReaderAsync();
|
||||||
|
while (await reader.ReadAsync())
|
||||||
|
{
|
||||||
|
if (string.Equals(reader["name"]?.ToString(), "ExpiresAt", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
hasExpiresAt = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!hasExpiresAt)
|
||||||
|
{
|
||||||
|
await using var alterCmd = connection.CreateCommand();
|
||||||
|
alterCmd.CommandText = "ALTER TABLE Slides ADD COLUMN ExpiresAt TEXT NULL;";
|
||||||
|
await alterCmd.ExecuteNonQueryAsync();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!app.Environment.IsDevelopment())
|
if (!app.Environment.IsDevelopment())
|
||||||
|
|||||||
Reference in New Issue
Block a user