plcsharp/PLCSharpWpf/Models/ProjectConfiguration.cs

135 lines
6.6 KiB
C#

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<string, string[]> Groups = new Dictionary<string, string[]>
{
["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"]
};
internal 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;
}
internal 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<string>()));
args["Path"] = Path.GetFileName(path.GetValue<string>());
}
}
internal static void Restore(DatasContext db, string[] tables, JsonObject document, bool update = false)
{
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)})";
if (update)
{
var key = entity.FindPrimaryKey().Properties.Single();
var assignments = fields.Select((p, i) => (p, i)).Where(x => x.p != key)
.Select(x => $"{Quote(x.p.GetColumnName())}={parameters[x.i]}");
insert.CommandText = $"UPDATE {Quote(table)} SET {string.Join(", ", assignments)} WHERE {Quote(key.GetColumnName())}={parameters[Array.IndexOf(fields, key)]}";
}
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 long.TryParse(value.ToJsonString(), System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var n) => n,
JsonValueKind.Number => value.Deserialize<double>(),
_ => 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;
}
if (insert.ExecuteNonQuery() != 1) throw new ProjectConflictException($"{table} 对象已改变。");
}
}
}
}