using System.Text.Json; using Store.Modules.CloudProduct.Entities; using var config = JsonDocument.Parse(File.ReadAllText("Plugins/CloudProduct/appsettings.json")); var connection = Environment.GetEnvironmentVariable("Plugins__CloudProduct__ProductInspection__ConnectionString") ?? config.RootElement.GetProperty("ProductInspection").GetProperty("ConnectionString").GetString(); using var db = new FreeSql.FreeSqlBuilder().UseConnectionString(FreeSql.DataType.MySql, connection).Build(); const string tableQuery = "SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() ORDER BY TABLE_NAME"; const string columnsQuery = "SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'image_analysis_cache' ORDER BY ORDINAL_POSITION"; if (args.Contains("--initialize")) { // 旧表只移除两个派生字段,保留缓存键、响应原文及更新时间。 var existing = await db.Ado.QueryAsync(tableQuery); if (!existing.Contains("image_analysis_cache")) db.CodeFirst.SyncStructure(typeof(ImageAnalysisCache)); var columns = await db.Ado.QueryAsync(columnsQuery); var oldResult = new[] { "FormattedData", "识别结果" }.SingleOrDefault(columns.Contains); if (oldResult != null) await db.Ado.ExecuteNonQueryAsync($"ALTER TABLE image_analysis_cache CHANGE COLUMN `{oldResult}` RecognitionResult LONGTEXT NOT NULL"); var drops = new[] { "DetectionText", "LogoBrands" }.Where(columns.Contains).Select(name => $"DROP COLUMN `{name}`").ToArray(); if (drops.Length > 0) await db.Ado.ExecuteNonQueryAsync("ALTER TABLE image_analysis_cache " + string.Join(", ", drops)); // 旧键不能还原为图片 MD5,禁止在有旧缓存的环境中直接缩短主键。 if (await db.Select().Where(x => x.CacheKey.Length > 32).AnyAsync()) throw new InvalidOperationException("请先归档或清理旧的 SHA-256 图片缓存,再执行升级。"); db.CodeFirst.SyncStructure(typeof(ImageAnalysisCache)); await db.Ado.ExecuteNonQueryAsync("DROP TABLE IF EXISTS inspection_task_item, inspection_task, inspection_result, inspection_user_rule"); } var tables = await db.Ado.QueryAsync(tableQuery); Console.WriteLine(string.Join(", ", tables)); var cacheColumns = await db.Ado.QueryAsync(columnsQuery); Console.WriteLine("Cache columns: " + string.Join(", ", cacheColumns)); Console.WriteLine($"Cache rows: {await db.Select().CountAsync()}"); if (args.Contains("--schema")) return; if (!cacheColumns.ToHashSet().SetEquals(new[] { "CacheKey", "RecognitionResult", "UpdatedAt" })) throw new Exception("图片识别缓存结构不匹配。"); if (!tables.Contains("image_analysis_cache")) throw new Exception("商品检测专用库缺少图片缓存表。"); var keyLength = await db.Ado.ExecuteScalarAsync("SELECT CHARACTER_MAXIMUM_LENGTH FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'image_analysis_cache' AND COLUMN_NAME = 'CacheKey'"); if (Convert.ToInt32(keyLength) != 32) throw new Exception("CacheKey 应为 32 位 MD5。"); await HttpChecks.RunAsync(db);