485 lines
17 KiB
C#
485 lines
17 KiB
C#
using DryIoc.ImTools;
|
||
using Microsoft.EntityFrameworkCore;
|
||
using Microsoft.EntityFrameworkCore.Metadata;
|
||
using PLCSharp.Core.Common;
|
||
using PLCSharp.VVMs.Authority;
|
||
using PLCSharp.VVMs.Connects;
|
||
using PLCSharp.VVMs.Cylinders;
|
||
using PLCSharp.VVMs.GlobalVariables;
|
||
using PLCSharp.VVMs.Homepage;
|
||
using PLCSharp.VVMs.MotionController;
|
||
using PLCSharp.VVMs.Recipe;
|
||
using PLCSharp.VVMs.Robots;
|
||
using PLCSharp.VVMs.Vision;
|
||
using PLCSharp.VVMs.Vision.Camera;
|
||
using PLCSharp.VVMs.Workflows;
|
||
using System.Data;
|
||
using System.Data.Common;
|
||
using System.IO;
|
||
using System.Text.RegularExpressions;
|
||
|
||
namespace PLCSharp.Models
|
||
{
|
||
/// <summary>
|
||
/// DatasContext
|
||
/// </summary>
|
||
public class DatasContext : DbContext
|
||
{
|
||
/// <summary>
|
||
/// 数据库文件位置:优先用可执行文件同级的 Config/Datas.db,
|
||
/// 若老安装把库放在了「启动工作目录」下则继续沿用,避免升级后看不到原有数据。
|
||
/// </summary>
|
||
public static string DefaultDatabasePath { get; } = ResolveDatabasePath();
|
||
|
||
/// <summary>
|
||
/// 本实例使用的连接串;为空表示使用 DefaultDatabasePath
|
||
/// </summary>
|
||
private readonly string _connectionString;
|
||
|
||
/// <summary>
|
||
/// DatasContext
|
||
/// </summary>
|
||
public DatasContext()
|
||
{
|
||
EnsureSchema();
|
||
}
|
||
|
||
/// <summary>
|
||
/// DatasContext:指定数据库文件路径(测试与维护用)
|
||
/// </summary>
|
||
/// <param name="databasePath">数据库文件路径</param>
|
||
public DatasContext(string databasePath)
|
||
{
|
||
_connectionString = $"Data Source={databasePath}";
|
||
EnsureSchema();
|
||
}
|
||
|
||
/// <summary>
|
||
/// 建库/建表/补齐缺失的列:模型改了字段不再需要手工迁移
|
||
/// </summary>
|
||
private void EnsureSchema()
|
||
{
|
||
var path = string.IsNullOrEmpty(_connectionString)
|
||
? DefaultDatabasePath
|
||
: _connectionString.Replace("Data Source=", string.Empty);
|
||
|
||
var dir = Path.GetDirectoryName(path);
|
||
if (!string.IsNullOrEmpty(dir))
|
||
{
|
||
Directory.CreateDirectory(dir);
|
||
}
|
||
|
||
// 首次运行:整库创建完毕,无需再补
|
||
if (Database.EnsureCreated()) return;
|
||
|
||
SchemaMaintenance.AddMissingTablesAndColumns(this);
|
||
}
|
||
|
||
private static string ResolveDatabasePath()
|
||
{
|
||
var legacy = Path.Combine(Directory.GetCurrentDirectory(), "Config", "Datas.db");
|
||
if (File.Exists(legacy))
|
||
{
|
||
return legacy;
|
||
}
|
||
|
||
return Path.Combine(AppContext.BaseDirectory, "Config", "Datas.db");
|
||
}
|
||
|
||
/// <summary>
|
||
/// Users
|
||
/// </summary>
|
||
public DbSet<User> Users { get; set; }
|
||
|
||
/// <summary>
|
||
/// 系统全局变量集合
|
||
/// </summary>
|
||
public DbSet<SystemVariable> SystemVariables { get; set; }
|
||
|
||
/// <summary>
|
||
/// 用户全局变量集合
|
||
/// <summary>
|
||
public DbSet<Variable> Variables { get; set; }
|
||
|
||
/// <summary>
|
||
/// VisionFunctions
|
||
/// </summary>
|
||
public DbSet<VisionFunction> VisionFunctions { get; set; }
|
||
|
||
/// <summary>
|
||
/// 全局图像列表
|
||
/// </summary>
|
||
public DbSet<ImageData> ImageDatas { get; set; }
|
||
|
||
/// <summary>
|
||
/// 局部图像列表
|
||
/// </summary>
|
||
public DbSet<LocalImageData> LocalImageDatas { get; set; }
|
||
|
||
/// <summary>
|
||
/// 连接模型·
|
||
/// </summary>
|
||
public DbSet<Connect> Connects { get; set; }
|
||
|
||
/// <summary>
|
||
/// Cameras
|
||
/// </summary>
|
||
public DbSet<CameraBase> Cameras { get; set; }
|
||
|
||
/// <summary>
|
||
/// Controllers
|
||
/// </summary>
|
||
public DbSet<Controller> Controllers { get; set; }
|
||
|
||
/// <summary>
|
||
/// Axes
|
||
/// </summary>
|
||
public DbSet<Axis> Axes { get; set; }
|
||
|
||
/// <summary>
|
||
/// 轴Points
|
||
/// </summary>
|
||
public DbSet<AxisPoint> AxisPoints { get; set; }
|
||
|
||
/// <summary>
|
||
/// 轴Points
|
||
/// </summary>
|
||
public DbSet<Matrix> Matrices { get; set; }
|
||
|
||
/// <summary>
|
||
/// 插补Groups
|
||
/// </summary>
|
||
public DbSet<InterpolationGroup> InterpolationGroups { get; set; }
|
||
|
||
/// <summary>
|
||
/// DI
|
||
/// </summary>
|
||
public DbSet<DI> DI { get; set; }
|
||
|
||
/// <summary>
|
||
/// DQ
|
||
/// </summary>
|
||
public DbSet<DQ> DQ { get; set; }
|
||
|
||
/// <summary>
|
||
/// Robots
|
||
/// </summary>
|
||
public DbSet<Robot> Robots { get; set; }
|
||
|
||
/// <summary>
|
||
/// 机器人Points
|
||
/// </summary>
|
||
public DbSet<RobotPoint> RobotPoints { get; set; }
|
||
|
||
/// <summary>
|
||
/// 机器人矩阵
|
||
/// </summary>
|
||
public DbSet<RobotMatrix> RobotMatrices { get; set; }
|
||
|
||
/// <summary>
|
||
/// 气缸
|
||
/// </summary>
|
||
public DbSet<Cylinder> Cylinders { get; set; }
|
||
|
||
/// <summary>
|
||
/// 错误Logs
|
||
/// </summary>
|
||
public DbSet<ErrorLog> ErrorLogs { get; set; }
|
||
|
||
/// <summary>
|
||
/// CustomControls
|
||
/// </summary>
|
||
public DbSet<CustomControl> CustomControls { get; set; }
|
||
|
||
/// <summary>
|
||
/// CanvasConfigs
|
||
/// </summary>
|
||
public DbSet<CanvasConfig> CanvasConfigs { get; set; }
|
||
|
||
/// <summary>
|
||
/// CurrentRecipe
|
||
/// </summary>
|
||
public Recipe CurrentRecipe { get; set; }
|
||
|
||
/// <summary>
|
||
/// OnConfiguring
|
||
/// </summary>
|
||
/// <param name="options">options</param>
|
||
protected override void OnConfiguring(DbContextOptionsBuilder options)
|
||
=> options.UseSqlite(string.IsNullOrEmpty(_connectionString)
|
||
? $"Data Source={DefaultDatabasePath}"
|
||
: _connectionString);
|
||
|
||
internal readonly object Sync = new();
|
||
internal Action<HashSet<string>> ConfigurationChanged;
|
||
|
||
internal static DatasContext CreateWorkingCopy() => new DatasContext(true);
|
||
|
||
private DatasContext(bool workingCopy)
|
||
{
|
||
_connectionString = "Data Source=:memory:";
|
||
Database.OpenConnection();
|
||
Database.EnsureCreated();
|
||
}
|
||
|
||
/// <summary>
|
||
/// 保存
|
||
/// </summary>
|
||
public void Save()
|
||
{
|
||
lock (Sync)
|
||
{
|
||
var tables = ConfigurationChanged == null ? null : ChangeTracker.Entries()
|
||
.Where(e => e.State is EntityState.Added or EntityState.Modified or EntityState.Deleted)
|
||
.Select(e => e.Metadata.GetTableName()).ToHashSet();
|
||
SaveChanges();
|
||
if (tables != null) ConfigurationChanged(tables);
|
||
}
|
||
}
|
||
}
|
||
|
||
// Accounts and logs belong to this installation. They never enter a project directory.
|
||
public sealed class MachineDataContext : DatasContext
|
||
{
|
||
public MachineDataContext() { }
|
||
internal MachineDataContext(string path) : base(path) { }
|
||
|
||
protected override void OnModelCreating(ModelBuilder builder)
|
||
{
|
||
base.OnModelCreating(builder);
|
||
var projectTypes = builder.Model.GetEntityTypes().Select(entity => entity.ClrType)
|
||
.Where(type => type != typeof(User) && type != typeof(ErrorLog)).ToList();
|
||
foreach (var type in projectTypes) builder.Ignore(type);
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// SQLite 库的增量维护:补建缺失的表、补齐缺失的列。
|
||
/// </summary>
|
||
/// <remarks>
|
||
/// <para>
|
||
/// 旧实现是「对每个 DbSet 试跑一次 SELECT,抛异常就把 <c>GenerateCreateScript()</c> 按
|
||
/// <c>CREATE TABLE "xxx"</c> 做字符串 Split、取最后一段去执行」。它的问题:只处理缺表,
|
||
/// 完全不处理「模型加了字段」(老库读不到新列),Split 可能取到错误片段,
|
||
/// 且会把别的表的片段拼进来,表名也直接拼进 SQL。
|
||
/// </para>
|
||
/// <para>
|
||
/// 现在改为:把 EF 模型里的期望结构与 SQLite 实际结构(sqlite_master / PRAGMA table_info)对比,
|
||
/// 缺表就按 EF 生成脚本自身的依赖顺序只执行属于该表的语句;缺列就 ALTER TABLE ADD COLUMN。
|
||
/// 因此给实体新增字段后,老库打开时会自动补上,不再需要手工迁移。
|
||
/// </para>
|
||
/// </remarks>
|
||
internal static class SchemaMaintenance
|
||
{
|
||
/// <summary>
|
||
/// CREATE TABLE 语句的目标表名
|
||
/// </summary>
|
||
private static readonly Regex CreateTableTarget = new(@"CREATE\s+TABLE\s+""([^""]+)""", RegexOptions.IgnoreCase | RegexOptions.Compiled);
|
||
|
||
/// <summary>
|
||
/// CREATE (UNIQUE) INDEX 语句的目标表名
|
||
/// </summary>
|
||
private static readonly Regex OnTableTarget = new(@"\bON\s+""([^""]+)""", RegexOptions.IgnoreCase | RegexOptions.Compiled);
|
||
|
||
/// <summary>
|
||
/// 补建缺失的表、补齐缺失的列
|
||
/// </summary>
|
||
/// <param name="dbContext">上下文</param>
|
||
internal static void AddMissingTablesAndColumns(DbContext dbContext)
|
||
{
|
||
// 1) 期望结构:来自 EF 模型本身,而不是反射 DbSet 名字
|
||
var expected = new Dictionary<string, List<ExpectedColumn>>(StringComparer.OrdinalIgnoreCase);
|
||
foreach (var entityType in dbContext.Model.GetEntityTypes())
|
||
{
|
||
var table = entityType.GetTableName();
|
||
if (string.IsNullOrWhiteSpace(table)) continue;
|
||
|
||
var storeObject = StoreObjectIdentifier.Table(table, entityType.GetSchema());
|
||
var columns = new List<ExpectedColumn>();
|
||
foreach (var property in entityType.GetProperties())
|
||
{
|
||
if (property.IsPrimaryKey()) continue; // ALTER 加不了主键列,缺主键只能走「缺表重建」
|
||
|
||
// 影子属性(TPH 判别列等)不自动补:给判别列填个错值,比缺列直接报错更危险
|
||
if (property.IsShadowProperty()) continue;
|
||
|
||
// 计算列由数据库维护,不能 ALTER ADD COLUMN
|
||
if (!string.IsNullOrEmpty(property.GetComputedColumnSql())) continue;
|
||
|
||
var columnName = property.GetColumnName(storeObject);
|
||
if (string.IsNullOrWhiteSpace(columnName)) continue;
|
||
|
||
columns.Add(ExpectedColumn.Of(columnName, property));
|
||
}
|
||
|
||
expected[table] = columns;
|
||
}
|
||
|
||
var connection = dbContext.Database.GetDbConnection();
|
||
var wasOpen = connection.State == ConnectionState.Open;
|
||
if (!wasOpen) connection.Open();
|
||
|
||
try
|
||
{
|
||
var actualTables = ReadTableNames(connection);
|
||
|
||
// 2) 缺表:按 GenerateCreateScript() 的原有顺序执行,保证被引用的表先建出来
|
||
var missing = new HashSet<string>(
|
||
expected.Keys.Where(t => !actualTables.Contains(t)),
|
||
StringComparer.OrdinalIgnoreCase);
|
||
|
||
if (missing.Count > 0)
|
||
{
|
||
foreach (var statement in SplitStatements(dbContext.Database.GenerateCreateScript()))
|
||
{
|
||
var target = TargetTableOf(statement);
|
||
if (target.Length > 0 && missing.Contains(target))
|
||
{
|
||
ExecuteNonQuery(connection, statement);
|
||
}
|
||
}
|
||
}
|
||
|
||
// 3) 缺列:模型新增的字段自动补上,老库不会因为加了字段而读不到列
|
||
foreach (var table in expected.Keys)
|
||
{
|
||
if (!actualTables.Contains(table)) continue; // 上一步刚整表建好
|
||
|
||
var actualColumns = ReadColumnNames(connection, table);
|
||
foreach (var column in expected[table])
|
||
{
|
||
if (actualColumns.Contains(column.Name)) continue;
|
||
|
||
ExecuteNonQuery(connection,
|
||
$@"ALTER TABLE {Quote(table)} ADD COLUMN {Quote(column.Name)} {column.StoreType}{(column.NotNull ? " NOT NULL" : " NULL")} DEFAULT {column.DefaultSql};");
|
||
}
|
||
}
|
||
}
|
||
finally
|
||
{
|
||
if (!wasOpen && connection.State == ConnectionState.Open) connection.Close();
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 期望列(名字 + 存储类型 + 给已有行填的默认值)
|
||
/// </summary>
|
||
private readonly record struct ExpectedColumn(string Name, string StoreType, string DefaultSql, bool NotNull)
|
||
{
|
||
internal static ExpectedColumn Of(string columnName, IProperty property)
|
||
{
|
||
var storeType = property.GetColumnType();
|
||
var underlying = Nullable.GetUnderlyingType(property.ClrType) ?? property.ClrType;
|
||
var nullable = Nullable.GetUnderlyingType(property.ClrType) is not null || property.IsNullable;
|
||
|
||
if (nullable)
|
||
{
|
||
return new ExpectedColumn(columnName, storeType, "NULL", false);
|
||
}
|
||
|
||
// 非空列必须给默认值,否则 SQLite 拒绝 ADD COLUMN(已有行无法填空)
|
||
if (underlying == typeof(string) || underlying == typeof(char))
|
||
{
|
||
return new ExpectedColumn(columnName, storeType, "''", true);
|
||
}
|
||
|
||
if (underlying == typeof(Guid))
|
||
{
|
||
return new ExpectedColumn(columnName, storeType, "'00000000-0000-0000-0000-000000000000'", true);
|
||
}
|
||
|
||
if (underlying == typeof(DateTime) || underlying == typeof(DateTimeOffset))
|
||
{
|
||
return new ExpectedColumn(columnName, storeType, "'0001-01-01 00:00:00'", true);
|
||
}
|
||
|
||
if (underlying == typeof(TimeSpan))
|
||
{
|
||
return new ExpectedColumn(columnName, storeType, "'00:00:00'", true);
|
||
}
|
||
|
||
if (underlying == typeof(byte[]))
|
||
{
|
||
return new ExpectedColumn(columnName, storeType, "NULL", false);
|
||
}
|
||
|
||
if (underlying.IsEnum
|
||
|| underlying == typeof(bool) || underlying == typeof(byte) || underlying == typeof(sbyte)
|
||
|| underlying == typeof(short) || underlying == typeof(ushort)
|
||
|| underlying == typeof(int) || underlying == typeof(uint)
|
||
|| underlying == typeof(long) || underlying == typeof(ulong)
|
||
|| underlying == typeof(float) || underlying == typeof(double) || underlying == typeof(decimal))
|
||
{
|
||
return new ExpectedColumn(columnName, storeType, "0", true);
|
||
}
|
||
|
||
// 其它类型:退化成可空列,保证至少不会把老库卡住
|
||
return new ExpectedColumn(columnName, storeType, "NULL", false);
|
||
}
|
||
}
|
||
|
||
private static HashSet<string> ReadTableNames(DbConnection connection)
|
||
{
|
||
var names = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||
|
||
using var command = connection.CreateCommand();
|
||
command.CommandText = @"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'";
|
||
|
||
using var reader = command.ExecuteReader();
|
||
while (reader.Read())
|
||
{
|
||
names.Add(reader.GetString(0));
|
||
}
|
||
|
||
return names;
|
||
}
|
||
|
||
private static HashSet<string> ReadColumnNames(DbConnection connection, string table)
|
||
{
|
||
var names = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||
|
||
using var command = connection.CreateCommand();
|
||
command.CommandText = $@"PRAGMA table_info({Quote(table)})";
|
||
|
||
using var reader = command.ExecuteReader();
|
||
while (reader.Read())
|
||
{
|
||
names.Add(reader.GetString(1));
|
||
}
|
||
|
||
return names;
|
||
}
|
||
|
||
private static IEnumerable<string> SplitStatements(string script)
|
||
{
|
||
foreach (var raw in script.Split([";\r\n", ";\n"], StringSplitOptions.RemoveEmptyEntries))
|
||
{
|
||
var statement = raw.Trim();
|
||
if (statement.Length == 0) continue;
|
||
|
||
yield return statement + ";";
|
||
}
|
||
}
|
||
|
||
private static string TargetTableOf(string statement)
|
||
{
|
||
var create = CreateTableTarget.Match(statement);
|
||
if (create.Success) return create.Groups[1].Value;
|
||
|
||
var on = OnTableTarget.Match(statement);
|
||
return on.Success ? on.Groups[1].Value : string.Empty;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 标识符加引号并去掉内嵌的双引号,避免把名字拼成可执行的 SQL
|
||
/// </summary>
|
||
private static string Quote(string identifier) => "\"" + identifier.Replace("\"", string.Empty) + "\"";
|
||
|
||
private static void ExecuteNonQuery(DbConnection connection, string sql)
|
||
{
|
||
using var command = connection.CreateCommand();
|
||
command.CommandText = sql;
|
||
_ = command.ExecuteNonQuery();
|
||
}
|
||
}
|
||
} |