using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; using PLCSharp.VVMs.Vision; using System.Data; using System.IO; using System.Text.Json; using System.Text.Json.Nodes; namespace PLCSharp.Models; // The editor keeps using its EF queries against a private in-memory working copy. // Only the explicitly listed configuration tables are part of the project format. internal static class ProjectConfiguration { internal static readonly IReadOnlyDictionary Groups = new Dictionary { ["hardware"] = ["Controllers", "Axes", "DI", "DQ", "Connects", "Robots", "Cylinders", "Cameras"], ["variables"] = ["Variables", "SystemVariables"], ["points"] = ["AxisPoints", "Matrices", "InterpolationGroups", "RobotPoints", "RobotMatrices"], ["vision"] = ["VisionFunctions", "ImageDatas", "LocalImageDatas"], ["interface"] = ["CanvasConfigs", "CustomControls"] }; private static IEntityType Entity(DatasContext db, string table) => db.Model.GetEntityTypes().Single(e => e.GetTableName() == table); private static string Quote(string identifier) => "\"" + identifier.Replace("\"", "\"\"") + "\""; internal static JsonObject Capture(DatasContext db, string[] tables, bool embedInputs = true) { var document = new JsonObject(); foreach (var table in tables) { var entity = Entity(db, table); var fields = entity.GetProperties().ToArray(); using var query = db.Database.GetDbConnection().CreateCommand(); var columns = string.Join(", ", fields.Select(p => Quote(p.GetColumnName()))); query.CommandText = $"SELECT {columns} FROM {Quote(table)} ORDER BY {Quote(entity.FindPrimaryKey().Properties.Single().GetColumnName())}"; using var reader = query.ExecuteReader(); var rows = new JsonArray(); while (reader.Read()) { var row = new JsonObject(); for (int i = 0; i < fields.Length; i++) { var p = fields[i]; JsonNode value = null; if (!reader.IsDBNull(i)) { var raw = reader.GetValue(i); value = IsJson(p) ? (JsonNode.Parse((string)raw) ?? JsonValue.Create("null")) : JsonSerializer.SerializeToNode(raw); if (embedInputs && table == "VisionFunctions" && p.GetColumnName() == "VisionFlows") EmbedImageInputs(value); } row.Add(p.GetColumnName(), value); } rows.Add(row); } document.Add(table, rows); } return document; } private static bool IsJson(IProperty property) => property.ClrType == typeof(string) && property.Name.StartsWith("Serialized", StringComparison.Ordinal); private static void EmbedImageInputs(JsonNode flows) { foreach (var flow in flows.AsArray()) { if ((int?)flow["Type"] != (int)VisionFlowType.从文件获取图片 || flow["StringParams"] is not JsonObject args || args["Path"] is not JsonValue path) continue; if (args["ImageBase64"] == null) args["ImageBase64"] = Convert.ToBase64String(File.ReadAllBytes(path.GetValue())); args["Path"] = Path.GetFileName(path.GetValue()); } } internal static void Restore(DatasContext db, string[] tables, JsonObject document) { foreach (var table in tables) { var entity = Entity(db, table); var fields = entity.GetProperties().ToArray(); if (document[table] is not JsonArray rows) throw new InvalidDataException($"工程配置缺少 {table}。"); using var insert = db.Database.GetDbConnection().CreateCommand(); var columns = string.Join(", ", fields.Select(p => Quote(p.GetColumnName()))); var parameters = fields.Select((p, i) => "$p" + i).ToArray(); insert.CommandText = $"INSERT INTO {Quote(table)} ({columns}) VALUES ({string.Join(", ", parameters)})"; foreach (var name in parameters) { var parameter = insert.CreateParameter(); parameter.ParameterName = name; insert.Parameters.Add(parameter); } foreach (var item in rows) { var row = item.AsObject(); for (int i = 0; i < fields.Length; i++) { var p = fields[i]; if (!row.TryGetPropertyValue(p.GetColumnName(), out var value)) throw new InvalidDataException($"{table} 缺少字段 {p.GetColumnName()}。"); object raw = DBNull.Value; if (value != null) { if (IsJson(p)) raw = value.GetValueKind() == JsonValueKind.String && (string)value == "null" ? "null" : value.ToJsonString(); else if (p.ClrType == typeof(byte[])) raw = Convert.FromBase64String((string)value); else raw = value.GetValueKind() switch { JsonValueKind.String => (string)value, JsonValueKind.Number when value.AsValue().TryGetValue(out var n) => n, JsonValueKind.Number => (double)value, _ => throw new InvalidDataException($"{table}.{p.Name} 类型无效。") }; // SQLite stores EF GUID keys in upper-case text. if (p.ClrType == typeof(Guid)) raw = Guid.Parse((string)raw).ToString("D").ToUpperInvariant(); } insert.Parameters[i].Value = raw; } insert.ExecuteNonQuery(); } } } }