plcsharp/Tests/PLCSharp.Tests/DatasContextTests.cs
tfarcraw ec0c476c79 修复数据库无迁移能力:用模型对比补表补列,替掉字符串 Split 建表 hack
原做法:构造时 EnsureCreated() + 对每个 DbSet 反射名字试跑 SELECT,抛异常就把 GenerateCreateScript() 按 CREATE TABLE 名字 做 Split、取最后一段拼回去执行。问题:
- 只处理「缺表」,完全不处理「模型加了字段」。给实体新增一个属性后,老库的表里没有该列,EF 的 SELECT 直接 no such column —— 整个模块打不开,只能删库重来;
- Split 取 Last() 会挑错片段(同名字符串在别的表定义/索引里出现时),拼出来的 SQL 可能混进别的表的片段;索引语句被丢掉;
- 表名直接拼进 SQL;用「试跑 SELECT 看是否抛异常」判断存在性,等于靠异常做流程控制。

改法(SchemaMaintenance):
- 期望结构取自 EF 模型本身(GetEntityTypes/GetTableName/GetColumnName/GetColumnType),不再反射 DbSet 属性名;
- 实际结构读 sqlite_master 与 PRAGMA table_info,不再用异常做流程控制;
- 缺表:按 GenerateCreateScript() 自身的依赖顺序,只执行属于该表的 CREATE TABLE / CREATE INDEX 语句(引用关系天然正确);
- 缺列:ALTER TABLE ADD COLUMN,按 CLR 类型给已有行补默认值(数值/枚举 0、字符串空串、Guid 全零、时间 0001-01-01),非空列带 NOT NULL DEFAULT,可空列填 NULL;
- 不自动补的三类:主键列(ALTER 加不了)、影子/判别列(填错值比缺列更危险,宁缺勿错)、计算列;
- 标识符统一加引号并剥掉内嵌双引号。

另外把库路径从相对 CWD 的 ./Config/Datas.db 改成可注入:新增 DatasContext(databasePath),默认路径改为「可执行文件同级 Config/Datas.db」,并且若老安装把库放在启动目录下则继续沿用(升级后不会看不到原数据);同时自动建目录。这样库不再是「谁启动就落在谁的当前目录」。

新增 5 个测试:建库落盘可重读(这条同时兜住上一个提交里「注册/改密/删除不 Save」那类不落盘缺陷的回归)、缺表自动补建、缺列自动 ALTER 并按默认值填充、重复打开幂等不会重复加列、指定路径不会写到默认库。测试 59/59 通过,构建 0 error。
2026-11-17 23:30:38 +08:00

152 lines
4.8 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#nullable enable
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using PLCSharp.Models;
using PLCSharp.VVMs.Authority;
namespace PLCSharp.Tests;
/// <summary>
/// DatasContext 的库/表维护测试。
/// 同时兜住两条历史缺陷:
/// 1) 写操作不 Save 就丢数据(注册/改密/删除)——用「换一个 context 重新打开还在不在」直接验证落盘;
/// 2) 老库缺表/缺列时只会用字符串 Split 猜建表语句,模型加字段后老库直接读不到列。
/// </summary>
public class DatasContextTests : IDisposable
{
private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"plcsharp_test_{Guid.NewGuid():N}.db");
public void Dispose()
{
SqliteConnection.ClearAllPools();
foreach (var suffix in new[] { "", "-wal", "-shm" })
{
var file = _dbPath + suffix;
if (File.Exists(file)) File.Delete(file);
}
}
/// <summary>
/// 对库直接执行 SQL(模拟老库结构)
/// </summary>
private void ExecuteRaw(string sql)
{
using var connection = new SqliteConnection($"Data Source={_dbPath}");
connection.Open();
using var command = connection.CreateCommand();
command.CommandText = sql;
_ = command.ExecuteNonQuery();
}
private List<string> ReadColumns(string table)
{
var names = new List<string>();
using var connection = new SqliteConnection($"Data Source={_dbPath}");
connection.Open();
using var command = connection.CreateCommand();
command.CommandText = $@"PRAGMA table_info(""{table}"")";
using var reader = command.ExecuteReader();
while (reader.Read()) names.Add(reader.GetString(1));
return names;
}
[Fact]
public void 首次打开_应建库并可落盘重读()
{
using (var db = new DatasContext(_dbPath))
{
// 构造函数里已经完成建库;这里只验证「真的建出来了、能写进去」
db.Users.Add(new User("tester", "salt.hash", Authority.Engineer));
db.Save();
}
// 换一个 context 重新打开:数据必须还在(这就是「注册/改密不落盘」那类 bug 的照妖镜)
using (var db = new DatasContext(_dbPath))
{
var user = db.Users.SingleOrDefault(u => u.Name == "tester");
Assert.NotNull(user);
Assert.Equal("tester", user!.Name);
Assert.Equal(Authority.Engineer, user.Authority);
}
}
[Fact]
public void 老库缺表_应自动补建该表()
{
using (var db = new DatasContext(_dbPath))
{
db.Users.Add(new User("keep", "salt.hash", Authority.Administrator));
db.Save();
}
ExecuteRaw(@"DROP TABLE ""Users"";");
using (var db = new DatasContext(_dbPath))
{
db.Users.Add(new User("again", "salt.hash", Authority.Super));
db.Save();
}
using (var db = new DatasContext(_dbPath))
{
Assert.Equal(1, db.Users.Count());
Assert.NotNull(db.Users.SingleOrDefault(u => u.Name == "again"));
}
}
[Fact]
public void 老库缺列_应自动ALTER补齐并按默认值填充()
{
using (var db = new DatasContext(_dbPath))
{
db.Users.Add(new User("legacy", "salt.hash", Authority.Super));
db.Save();
}
// 模拟「模型里还没有 Authority 字段」的老库
ExecuteRaw(@"ALTER TABLE ""Users"" DROP COLUMN ""Authority"";");
Assert.DoesNotContain("Authority", ReadColumns("Users"));
using (var db = new DatasContext(_dbPath))
{
var user = db.Users.SingleOrDefault(u => u.Name == "legacy");
// 打开时就补上了列,老行按默认值填(枚举 = 0),而不是读不到列直接炸
Assert.NotNull(user);
Assert.Equal(default(Authority), user!.Authority);
}
Assert.Contains("Authority", ReadColumns("Users"));
}
[Fact]
public void 补齐过程应幂等_反复打开不会重复加列()
{
for (var i = 0; i < 3; i++)
{
using var db = new DatasContext(_dbPath);
_ = db.Users.Count();
}
var columns = ReadColumns("Users");
Assert.Contains("Name", columns);
Assert.Contains("Password", columns);
Assert.Contains("Authority", columns);
Assert.Equal(columns.Count, columns.Distinct().Count());
}
[Fact]
public void 指定路径构造_不应写到默认库()
{
using var db = new DatasContext(_dbPath);
var connectionString = db.Database.GetDbConnection().ConnectionString;
Assert.Contains(_dbPath, connectionString);
Assert.DoesNotContain("Datas.db", connectionString);
}
}