SchemaSyncHandler.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. package com.zxyj.config;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.springframework.jdbc.core.JdbcTemplate;
  4. import org.springframework.stereotype.Component;
  5. import org.springframework.transaction.annotation.Transactional;
  6. import javax.annotation.Resource;
  7. import java.util.HashMap;
  8. import java.util.Map;
  9. import java.util.Set;
  10. import java.util.concurrent.ConcurrentHashMap;
  11. import java.util.regex.Matcher;
  12. import java.util.regex.Pattern;
  13. /**
  14. * 运行时数据库结构自动同步处理器
  15. * 当SQL报错"字段不存在"时,自动检测并添加字段
  16. */
  17. @Slf4j
  18. @Component
  19. public class SchemaSyncHandler {
  20. @Resource
  21. private JdbcTemplate jdbcTemplate;
  22. // 已处理过的表缓存,避免重复检查
  23. private final Set<String> processedTables = ConcurrentHashMap.newKeySet();
  24. // 字段定义映射表:表名 -> (字段名 -> MySQL类型定义)
  25. private static final Map<String, Map<String, String>> SCHEMA_DEFINITIONS;
  26. static {
  27. // rewards 表字段
  28. Map<String, String> rewardsFields = new HashMap<>();
  29. rewardsFields.put("title", "VARCHAR(100) NOT NULL DEFAULT ''");
  30. rewardsFields.put("points_required", "INT NOT NULL DEFAULT 0");
  31. rewardsFields.put("category", "VARCHAR(32)");
  32. rewardsFields.put("status", "ENUM('available','pending','exchanged','rejected') DEFAULT 'available'");
  33. rewardsFields.put("exchange_approved", "TINYINT");
  34. rewardsFields.put("exchanged_at", "DATETIME");
  35. rewardsFields.put("is_template", "TINYINT DEFAULT 0");
  36. rewardsFields.put("child_id", "BIGINT NULL");
  37. rewardsFields.put("family_id", "BIGINT NOT NULL");
  38. // tasks 表字段
  39. Map<String, String> tasksFields = new HashMap<>();
  40. tasksFields.put("title", "VARCHAR(200) NOT NULL");
  41. tasksFields.put("description", "VARCHAR(500)");
  42. tasksFields.put("category", "VARCHAR(32)");
  43. tasksFields.put("points", "TINYINT DEFAULT 2");
  44. tasksFields.put("deadline", "DATETIME");
  45. tasksFields.put("child_id", "BIGINT NULL");
  46. tasksFields.put("family_id", "BIGINT NOT NULL");
  47. tasksFields.put("creator_id", "BIGINT NOT NULL");
  48. tasksFields.put("status", "ENUM('pending','completed','overdue','cancelled') DEFAULT 'pending'");
  49. tasksFields.put("executor_type", "ENUM('child','parent') DEFAULT 'child'");
  50. tasksFields.put("executor_id", "BIGINT");
  51. tasksFields.put("repeat_type", "ENUM('none','daily','weekly') DEFAULT 'none'");
  52. tasksFields.put("need_review", "TINYINT DEFAULT 0");
  53. tasksFields.put("bonus_rule", "VARCHAR(500)");
  54. tasksFields.put("points_expire_days", "INT DEFAULT 0");
  55. tasksFields.put("template_id", "BIGINT");
  56. tasksFields.put("is_template", "TINYINT DEFAULT 0");
  57. // users 表字段
  58. Map<String, String> usersFields = new HashMap<>();
  59. usersFields.put("openid", "VARCHAR(64) NOT NULL");
  60. usersFields.put("unionid", "VARCHAR(64)");
  61. usersFields.put("family_id", "BIGINT NOT NULL");
  62. usersFields.put("role", "ENUM('parent','child','teacher') NOT NULL");
  63. usersFields.put("nickname", "VARCHAR(50)");
  64. usersFields.put("avatar", "VARCHAR(255)");
  65. usersFields.put("password", "VARCHAR(128)");
  66. usersFields.put("roles", "VARCHAR(100)");
  67. usersFields.put("total_points", "INT DEFAULT 0");
  68. // children 表字段
  69. Map<String, String> childrenFields = new HashMap<>();
  70. childrenFields.put("user_id", "BIGINT NOT NULL");
  71. childrenFields.put("family_id", "BIGINT NOT NULL");
  72. childrenFields.put("nickname", "VARCHAR(50) NOT NULL");
  73. childrenFields.put("age", "TINYINT NOT NULL");
  74. childrenFields.put("dan_level", "VARCHAR(2)");
  75. childrenFields.put("penalty_enabled", "TINYINT DEFAULT 1");
  76. childrenFields.put("theme", "VARCHAR(32) DEFAULT 'default'");
  77. childrenFields.put("total_points", "INT DEFAULT 0");
  78. childrenFields.put("streak_days", "INT DEFAULT 0");
  79. childrenFields.put("birthday", "DATE");
  80. childrenFields.put("gender", "ENUM('male','female')");
  81. // points_log 表字段
  82. Map<String, String> pointsLogFields = new HashMap<>();
  83. pointsLogFields.put("child_id", "BIGINT NOT NULL");
  84. pointsLogFields.put("task_id", "BIGINT");
  85. pointsLogFields.put("amount", "INT NOT NULL");
  86. pointsLogFields.put("type", "ENUM('earn','spend','bonus','penalty','adjust','reset','refund') NOT NULL");
  87. pointsLogFields.put("description", "VARCHAR(255)");
  88. pointsLogFields.put("expire_at", "DATE");
  89. pointsLogFields.put("expired", "TINYINT DEFAULT 0");
  90. SCHEMA_DEFINITIONS = new HashMap<>();
  91. SCHEMA_DEFINITIONS.put("rewards", rewardsFields);
  92. SCHEMA_DEFINITIONS.put("tasks", tasksFields);
  93. SCHEMA_DEFINITIONS.put("users", usersFields);
  94. SCHEMA_DEFINITIONS.put("children", childrenFields);
  95. SCHEMA_DEFINITIONS.put("points_log", pointsLogFields);
  96. }
  97. /**
  98. * 处理字段不存在的异常,自动添加字段后重试
  99. * @param exception 原始SQL异常消息
  100. * @param operation 要重试的操作
  101. * @return 重试结果,如果成功返回null,失败返回异常消息
  102. */
  103. @Transactional
  104. public String handleMissingColumn(String exception, Runnable operation) {
  105. // 匹配 "Unknown column 'xxx' in 'field list'" 或 "Field 'xxx' doesn't have a default value"
  106. Pattern pattern = Pattern.compile("Unknown column '(\\w+)' in '(?:field list|\\w+)'", Pattern.CASE_INSENSITIVE);
  107. Matcher matcher = pattern.matcher(exception);
  108. String fieldName = null;
  109. if (!matcher.find()) {
  110. // 也可能是 "Field 'xxx' doesn't have a default value" 情况
  111. pattern = Pattern.compile("Field '(\\w+)' doesn't have a default value", Pattern.CASE_INSENSITIVE);
  112. matcher = pattern.matcher(exception);
  113. if (!matcher.find()) {
  114. log.warn("无法解析字段缺失错误: {}", exception);
  115. return "无法解析字段缺失错误";
  116. }
  117. }
  118. fieldName = matcher.group(1);
  119. // 尝试提取表名
  120. String tableName = extractTableName(exception);
  121. if (tableName == null) {
  122. log.warn("无法从错误消息中提取表名: {}", exception);
  123. return "无法提取表名";
  124. }
  125. log.info("检测到字段缺失: {}.{}", tableName, fieldName);
  126. // 检查并添加字段
  127. boolean success = addMissingColumn(tableName, fieldName);
  128. if (!success) {
  129. return "无法自动添加字段: " + tableName + "." + fieldName;
  130. }
  131. // 重试操作
  132. try {
  133. operation.run();
  134. log.info("字段自动同步成功,重试操作完成: {}.{}", tableName, fieldName);
  135. return null;
  136. } catch (Exception e) {
  137. log.error("重试操作仍然失败: {}", e.getMessage());
  138. return "重试失败: " + e.getMessage();
  139. }
  140. }
  141. /**
  142. * 从异常消息中提取表名
  143. */
  144. private String extractTableName(String message) {
  145. // 优先尝试从表名中提取 (tableName.field)
  146. Pattern p = Pattern.compile("\\b(\\w+)\\.(\\w+)\\b", Pattern.CASE_INSENSITIVE);
  147. Matcher m = p.matcher(message);
  148. if (m.find()) {
  149. return m.group(1);
  150. }
  151. // 从 INSERT/UPDATE/INTO tableName 中提取
  152. p = Pattern.compile("(?:INSERT\\s+INTO|UPDATE|INTO)\\s+(\\w+)", Pattern.CASE_INSENSITIVE);
  153. m = p.matcher(message);
  154. if (m.find()) {
  155. return m.group(1);
  156. }
  157. return null;
  158. }
  159. /**
  160. * 添加缺失的列
  161. */
  162. private boolean addMissingColumn(String tableName, String fieldName) {
  163. tableName = tableName.toLowerCase();
  164. // 检查是否已经处理过
  165. String cacheKey = tableName + "." + fieldName;
  166. if (processedTables.contains(cacheKey)) {
  167. log.info("字段已在缓存中,跳过: {}", cacheKey);
  168. return true;
  169. }
  170. // 检查表定义中是否存在该字段
  171. Map<String, String> fields = SCHEMA_DEFINITIONS.get(tableName);
  172. if (fields == null) {
  173. log.warn("未找到表 {} 的字段定义", tableName);
  174. return false;
  175. }
  176. String columnDef = fields.get(fieldName.toLowerCase());
  177. if (columnDef == null) {
  178. log.warn("表 {} 中未定义字段 {}", tableName, fieldName);
  179. return false;
  180. }
  181. try {
  182. // 检查字段是否已存在
  183. boolean exists = checkColumnExists(tableName, fieldName);
  184. if (!exists) {
  185. String sql = String.format("ALTER TABLE %s ADD COLUMN %s %s", tableName, fieldName, columnDef);
  186. jdbcTemplate.execute(sql);
  187. log.info("已自动添加字段: {}.{}", tableName, fieldName);
  188. }
  189. // 加入缓存
  190. processedTables.add(cacheKey);
  191. return true;
  192. } catch (Exception e) {
  193. log.error("自动添加字段失败: {}.{} - {}", tableName, fieldName, e.getMessage());
  194. return false;
  195. }
  196. }
  197. /**
  198. * 检查字段是否已存在
  199. */
  200. private boolean checkColumnExists(String tableName, String fieldName) {
  201. try {
  202. String sql = "SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS " +
  203. "WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?";
  204. Integer count = jdbcTemplate.queryForObject(sql, Integer.class, tableName, fieldName);
  205. return count != null && count > 0;
  206. } catch (Exception e) {
  207. return false;
  208. }
  209. }
  210. /**
  211. * 运行时同步整个表的结构
  212. */
  213. @Transactional
  214. public void syncTableSchema(String tableName) {
  215. tableName = tableName.toLowerCase();
  216. Map<String, String> fields = SCHEMA_DEFINITIONS.get(tableName);
  217. if (fields == null) {
  218. log.warn("未找到表 {} 的定义,跳过同步", tableName);
  219. return;
  220. }
  221. log.info("开始同步表 {} 的结构...", tableName);
  222. for (Map.Entry<String, String> entry : fields.entrySet()) {
  223. String fieldName = entry.getKey();
  224. String columnDef = entry.getValue();
  225. try {
  226. boolean exists = checkColumnExists(tableName, fieldName);
  227. if (!exists) {
  228. String sql = String.format("ALTER TABLE %s ADD COLUMN %s %s", tableName, fieldName, columnDef);
  229. jdbcTemplate.execute(sql);
  230. log.info("已添加字段: {}.{}", tableName, fieldName);
  231. }
  232. } catch (Exception e) {
  233. log.warn("同步字段失败: {}.{} - {}", tableName, fieldName, e.getMessage());
  234. }
  235. }
  236. log.info("表 {} 结构同步完成", tableName);
  237. }
  238. /**
  239. * 同步所有已定义的表
  240. */
  241. public void syncAllTables() {
  242. log.info("开始同步所有表结构...");
  243. for (String tableName : SCHEMA_DEFINITIONS.keySet()) {
  244. try {
  245. syncTableSchema(tableName);
  246. } catch (Exception e) {
  247. log.error("同步表 {} 失败: {}", tableName, e.getMessage());
  248. }
  249. }
  250. log.info("所有表结构同步完成");
  251. }
  252. }