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 { /// /// DatasContext /// public class DatasContext : DbContext { /// /// 数据库文件位置:优先用可执行文件同级的 Config/Datas.db, /// 若老安装把库放在了「启动工作目录」下则继续沿用,避免升级后看不到原有数据。 /// public static string DefaultDatabasePath { get; } = ResolveDatabasePath(); /// /// 本实例使用的连接串;为空表示使用 DefaultDatabasePath /// private readonly string _connectionString; /// /// DatasContext /// public DatasContext() { EnsureSchema(); } /// /// DatasContext:指定数据库文件路径(测试与维护用) /// /// 数据库文件路径 public DatasContext(string databasePath) { _connectionString = $"Data Source={databasePath}"; EnsureSchema(); } /// /// 建库/建表/补齐缺失的列:模型改了字段不再需要手工迁移 /// 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"); } /// /// Users /// public DbSet Users { get; set; } /// /// Recipes /// public DbSet Recipes { get; set; } /// /// 系统全局变量集合 /// public DbSet SystemVariables { get; set; } /// /// 用户全局变量集合 /// public DbSet Variables { get; set; } /// /// Workflows /// public DbSet Workflows { get; set; } /// /// VisionFunctions /// public DbSet VisionFunctions { get; set; } /// /// 全局图像列表 /// public DbSet ImageDatas { get; set; } /// /// 局部图像列表 /// public DbSet LocalImageDatas { get; set; } /// /// 连接模型· /// public DbSet Connects { get; set; } /// /// Cameras /// public DbSet Cameras { get; set; } /// /// Controllers /// public DbSet Controllers { get; set; } /// /// Axes /// public DbSet Axes { get; set; } /// /// 轴Points /// public DbSet AxisPoints { get; set; } /// /// 轴Points /// public DbSet Matrices { get; set; } /// /// 插补Groups /// public DbSet InterpolationGroups { get; set; } /// /// DI /// public DbSet DI { get; set; } /// /// DQ /// public DbSet DQ { get; set; } /// /// Robots /// public DbSet Robots { get; set; } /// /// 机器人Points /// public DbSet RobotPoints { get; set; } /// /// 机器人矩阵 /// public DbSet RobotMatrices { get; set; } /// /// 气缸 /// public DbSet Cylinders { get; set; } /// /// 错误Logs /// public DbSet ErrorLogs { get; set; } /// /// CustomControls /// public DbSet CustomControls { get; set; } /// /// CanvasConfigs /// public DbSet CanvasConfigs { get; set; } /// /// CurrentRecipe /// public Recipe CurrentRecipe { get; set; } /// /// OnConfiguring /// /// options protected override void OnConfiguring(DbContextOptionsBuilder options) => options.UseSqlite(string.IsNullOrEmpty(_connectionString) ? $"Data Source={DefaultDatabasePath}" : _connectionString); private object _dbLock = new(); /// /// 保存 /// public void Save() { lock (_dbLock) { SaveChanges(); } } } /// /// SQLite 库的增量维护:补建缺失的表、补齐缺失的列。 /// /// /// /// 旧实现是「对每个 DbSet 试跑一次 SELECT,抛异常就把 GenerateCreateScript() 按 /// CREATE TABLE "xxx" 做字符串 Split、取最后一段去执行」。它的问题:只处理缺表, /// 完全不处理「模型加了字段」(老库读不到新列),Split 可能取到错误片段, /// 且会把别的表的片段拼进来,表名也直接拼进 SQL。 /// /// /// 现在改为:把 EF 模型里的期望结构与 SQLite 实际结构(sqlite_master / PRAGMA table_info)对比, /// 缺表就按 EF 生成脚本自身的依赖顺序只执行属于该表的语句;缺列就 ALTER TABLE ADD COLUMN。 /// 因此给实体新增字段后,老库打开时会自动补上,不再需要手工迁移。 /// /// internal static class SchemaMaintenance { /// /// CREATE TABLE 语句的目标表名 /// private static readonly Regex CreateTableTarget = new(@"CREATE\s+TABLE\s+""([^""]+)""", RegexOptions.IgnoreCase | RegexOptions.Compiled); /// /// CREATE (UNIQUE) INDEX 语句的目标表名 /// private static readonly Regex OnTableTarget = new(@"\bON\s+""([^""]+)""", RegexOptions.IgnoreCase | RegexOptions.Compiled); /// /// 补建缺失的表、补齐缺失的列 /// /// 上下文 internal static void AddMissingTablesAndColumns(DbContext dbContext) { // 1) 期望结构:来自 EF 模型本身,而不是反射 DbSet 名字 var expected = new Dictionary>(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(); 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( 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(); } } /// /// 期望列(名字 + 存储类型 + 给已有行填的默认值) /// 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 ReadTableNames(DbConnection connection) { var names = new HashSet(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 ReadColumnNames(DbConnection connection, string table) { var names = new HashSet(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 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; } /// /// 标识符加引号并去掉内嵌的双引号,避免把名字拼成可执行的 SQL /// 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(); } } }