CleanupExecutorLogic.php 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  1. <?php
  2. namespace App\Module\Cleanup\Logics;
  3. use App\Module\Cleanup\Models\CleanupTask;
  4. use App\Module\Cleanup\Models\CleanupPlan;
  5. use App\Module\Cleanup\Models\CleanupPlanContent;
  6. use App\Module\Cleanup\Models\CleanupLog;
  7. use App\Module\Cleanup\Enums\TASK_STATUS;
  8. use App\Module\Cleanup\Enums\CLEANUP_TYPE;
  9. use Illuminate\Support\Facades\DB;
  10. use Illuminate\Support\Facades\Log;
  11. use Illuminate\Support\Facades\Schema;
  12. use Illuminate\Database\Eloquent\Model;
  13. use Illuminate\Database\Eloquent\SoftDeletes;
  14. /**
  15. * 清理执行逻辑类
  16. *
  17. * 负责实际的数据清理执行操作
  18. */
  19. class CleanupExecutorLogic
  20. {
  21. /**
  22. * 预览计划的清理结果
  23. *
  24. * @param int $planId 计划ID
  25. * @return array 预览结果
  26. */
  27. public static function previewPlanCleanup(int $planId): array
  28. {
  29. try {
  30. $plan = CleanupPlan::with('contents')->findOrFail($planId);
  31. $previewData = [];
  32. $totalRecords = 0;
  33. $totalTables = 0;
  34. foreach ($plan->contents->where('is_enabled', true) as $content) {
  35. $tablePreview = static::previewTableCleanup($content);
  36. $previewData[] = $tablePreview;
  37. $totalRecords += $tablePreview['affected_records'];
  38. $totalTables++;
  39. }
  40. return [
  41. 'success' => true,
  42. 'data' => [
  43. 'plan' => [
  44. 'id' => $plan->id,
  45. 'plan_name' => $plan->plan_name,
  46. 'description' => $plan->description,
  47. ],
  48. 'summary' => [
  49. 'total_tables' => $totalTables,
  50. 'total_records' => $totalRecords,
  51. 'estimated_time' => static::estimateExecutionTime($totalRecords),
  52. ],
  53. 'tables' => $previewData,
  54. ]
  55. ];
  56. } catch (\Exception $e) {
  57. Log::error('预览计划清理失败', [
  58. 'plan_id' => $planId,
  59. 'error' => $e->getMessage()
  60. ]);
  61. return [
  62. 'success' => false,
  63. 'message' => '预览计划清理失败: ' . $e->getMessage(),
  64. 'data' => null
  65. ];
  66. }
  67. }
  68. /**
  69. * 预览任务的清理结果
  70. *
  71. * @param int $taskId 任务ID
  72. * @return array 预览结果
  73. */
  74. public static function previewTaskCleanup(int $taskId): array
  75. {
  76. try {
  77. $task = CleanupTask::with('plan.contents')->findOrFail($taskId);
  78. if (!$task->plan) {
  79. throw new \Exception('任务关联的计划不存在');
  80. }
  81. return static::previewPlanCleanup($task->plan->id);
  82. } catch (\Exception $e) {
  83. Log::error('预览任务清理失败', [
  84. 'task_id' => $taskId,
  85. 'error' => $e->getMessage()
  86. ]);
  87. return [
  88. 'success' => false,
  89. 'message' => '预览任务清理失败: ' . $e->getMessage(),
  90. 'data' => null
  91. ];
  92. }
  93. }
  94. /**
  95. * 执行清理任务
  96. *
  97. * @param int $taskId 任务ID
  98. * @param bool $dryRun 是否为预演模式
  99. * @return array 执行结果
  100. */
  101. public static function executeTask(int $taskId, bool $dryRun = false): array
  102. {
  103. try {
  104. $task = CleanupTask::with('plan.contents')->findOrFail($taskId);
  105. if (!$task->plan) {
  106. throw new \Exception('任务关联的计划不存在');
  107. }
  108. // 检查任务状态
  109. $currentStatus = TASK_STATUS::from($task->status);
  110. if ($currentStatus !== TASK_STATUS::PENDING) {
  111. throw new \Exception('任务状态不正确,无法执行');
  112. }
  113. if ($dryRun) {
  114. return static::previewTaskCleanup($taskId);
  115. }
  116. // 开始执行任务
  117. return static::executeTaskInternal($task);
  118. } catch (\Exception $e) {
  119. Log::error('执行清理任务失败', [
  120. 'task_id' => $taskId,
  121. 'dry_run' => $dryRun,
  122. 'error' => $e->getMessage(),
  123. 'trace' => $e->getTraceAsString()
  124. ]);
  125. return [
  126. 'success' => false,
  127. 'message' => '执行清理任务失败: ' . $e->getMessage(),
  128. 'data' => null
  129. ];
  130. }
  131. }
  132. /**
  133. * 内部执行任务逻辑
  134. *
  135. * @param CleanupTask $task 任务对象
  136. * @return array 执行结果
  137. */
  138. private static function executeTaskInternal(CleanupTask $task): array
  139. {
  140. $startTime = microtime(true);
  141. $totalDeleted = 0;
  142. $processedTables = 0;
  143. $errors = [];
  144. try {
  145. // 更新任务状态为执行中
  146. CleanupTaskLogic::updateTaskStatus($task->id, TASK_STATUS::RUNNING, [
  147. 'current_step' => '开始执行清理',
  148. ]);
  149. // 获取启用的内容配置
  150. $enabledContents = $task->plan->contents->where('is_enabled', true)->sortBy('priority');
  151. foreach ($enabledContents as $content) {
  152. try {
  153. // 更新当前步骤
  154. $targetName = $content->model_class ?: $content->table_name;
  155. try {
  156. CleanupTaskLogic::updateTaskProgress(
  157. $task->id,
  158. $processedTables,
  159. $totalDeleted,
  160. "正在清理: {$targetName}"
  161. );
  162. } catch (\Exception $progressException) {
  163. // 记录进度更新失败,但不影响清理继续执行
  164. Log::warning('更新任务进度失败', [
  165. 'task_id' => $task->id,
  166. 'error' => $progressException->getMessage()
  167. ]);
  168. }
  169. // 执行清理(支持Model类和表名两种模式)
  170. $result = static::executeCleanup($content, $task->id);
  171. if ($result['success']) {
  172. $totalDeleted += $result['deleted_records'];
  173. $processedTables++;
  174. } else {
  175. $targetName = $content->model_class ?: $content->table_name;
  176. $errors[] = "{$targetName}: " . $result['message'];
  177. }
  178. } catch (\Exception $e) {
  179. $targetName = $content->model_class ?: $content->table_name;
  180. $errors[] = "{$targetName}: " . $e->getMessage();
  181. Log::error("清理失败", [
  182. 'task_id' => $task->id,
  183. 'model_class' => $content->model_class,
  184. 'table_name' => $content->table_name,
  185. 'error' => $e->getMessage()
  186. ]);
  187. }
  188. }
  189. $executionTime = round(microtime(true) - $startTime, 3);
  190. // 更新任务完成状态
  191. $finalStatus = empty($errors) ? TASK_STATUS::COMPLETED : TASK_STATUS::FAILED;
  192. try {
  193. CleanupTaskLogic::updateTaskStatus($task->id, $finalStatus, [
  194. 'total_records' => $totalDeleted,
  195. 'deleted_records' => $totalDeleted,
  196. 'execution_time' => $executionTime,
  197. 'error_message' => empty($errors) ? null : implode('; ', $errors),
  198. 'current_step' => $finalStatus === TASK_STATUS::COMPLETED ? '清理完成' : '清理失败',
  199. ]);
  200. } catch (\Exception $statusException) {
  201. // 记录状态更新失败,但不影响返回结果
  202. Log::error('更新任务状态失败', [
  203. 'task_id' => $task->id,
  204. 'status' => $finalStatus->value,
  205. 'error' => $statusException->getMessage()
  206. ]);
  207. }
  208. return [
  209. 'success' => $finalStatus === TASK_STATUS::COMPLETED,
  210. 'message' => $finalStatus === TASK_STATUS::COMPLETED ? '清理任务执行成功' : '清理任务执行完成,但有错误',
  211. 'data' => [
  212. 'task_id' => $task->id,
  213. 'processed_tables' => $processedTables,
  214. 'total_tables' => $enabledContents->count(),
  215. 'deleted_records' => $totalDeleted,
  216. 'execution_time' => $executionTime,
  217. 'errors' => $errors,
  218. ]
  219. ];
  220. } catch (\Exception $e) {
  221. // 更新任务失败状态
  222. try {
  223. CleanupTaskLogic::updateTaskStatus($task->id, TASK_STATUS::FAILED, [
  224. 'error_message' => $e->getMessage(),
  225. 'execution_time' => round(microtime(true) - $startTime, 3),
  226. 'current_step' => '执行失败',
  227. ]);
  228. } catch (\Exception $statusException) {
  229. // 记录状态更新失败,但不影响原异常的抛出
  230. Log::error('更新任务失败状态时出错', [
  231. 'task_id' => $task->id,
  232. 'original_error' => $e->getMessage(),
  233. 'status_error' => $statusException->getMessage()
  234. ]);
  235. }
  236. throw $e;
  237. }
  238. }
  239. /**
  240. * 预览表清理
  241. *
  242. * @param CleanupPlanContent $content 计划内容
  243. * @return array 预览结果
  244. */
  245. private static function previewTableCleanup(CleanupPlanContent $content): array
  246. {
  247. try {
  248. $tableName = $content->table_name;
  249. $cleanupType = CLEANUP_TYPE::from($content->cleanup_type);
  250. // 检查表是否存在
  251. if (!Schema::hasTable($tableName)) {
  252. return [
  253. 'table_name' => $tableName,
  254. 'cleanup_type' => $cleanupType->getDescription(),
  255. 'affected_records' => 0,
  256. 'current_records' => 0,
  257. 'error' => '表不存在',
  258. ];
  259. }
  260. $currentRecords = DB::table($tableName)->count();
  261. $affectedRecords = static::calculateAffectedRecords($tableName, $cleanupType, $content->conditions);
  262. return [
  263. 'table_name' => $tableName,
  264. 'cleanup_type' => $cleanupType->getDescription(),
  265. 'affected_records' => $affectedRecords,
  266. 'current_records' => $currentRecords,
  267. 'remaining_records' => $currentRecords - $affectedRecords,
  268. 'conditions' => $content->conditions,
  269. 'batch_size' => $content->batch_size,
  270. 'backup_enabled' => $content->backup_enabled,
  271. ];
  272. } catch (\Exception $e) {
  273. return [
  274. 'table_name' => $content->table_name,
  275. 'cleanup_type' => CLEANUP_TYPE::from($content->cleanup_type)->getDescription(),
  276. 'affected_records' => 0,
  277. 'current_records' => 0,
  278. 'error' => $e->getMessage(),
  279. ];
  280. }
  281. }
  282. /**
  283. * 计算受影响的记录数
  284. *
  285. * @param string $tableName 表名
  286. * @param CLEANUP_TYPE $cleanupType 清理类型
  287. * @param array $conditions 清理条件
  288. * @return int 受影响的记录数
  289. */
  290. private static function calculateAffectedRecords(string $tableName, CLEANUP_TYPE $cleanupType, array $conditions): int
  291. {
  292. switch ($cleanupType) {
  293. case CLEANUP_TYPE::TRUNCATE:
  294. case CLEANUP_TYPE::DELETE_ALL:
  295. return DB::table($tableName)->count();
  296. case CLEANUP_TYPE::DELETE_BY_TIME:
  297. return static::countByTimeCondition($tableName, $conditions);
  298. case CLEANUP_TYPE::DELETE_BY_USER:
  299. return static::countByUserCondition($tableName, $conditions);
  300. case CLEANUP_TYPE::DELETE_BY_CONDITION:
  301. return static::countByCustomCondition($tableName, $conditions);
  302. default:
  303. return 0;
  304. }
  305. }
  306. /**
  307. * 按时间条件统计记录数
  308. *
  309. * @param string $tableName 表名
  310. * @param array $conditions 条件
  311. * @return int 记录数
  312. */
  313. private static function countByTimeCondition(string $tableName, array $conditions): int
  314. {
  315. $query = DB::table($tableName);
  316. if (!empty($conditions['time_field']) && !empty($conditions['before'])) {
  317. $timeField = $conditions['time_field'];
  318. $beforeTime = static::parseTimeCondition($conditions['before']);
  319. $query->where($timeField, '<', $beforeTime);
  320. }
  321. return $query->count();
  322. }
  323. /**
  324. * 按用户条件统计记录数
  325. *
  326. * @param string $tableName 表名
  327. * @param array $conditions 条件
  328. * @return int 记录数
  329. */
  330. private static function countByUserCondition(string $tableName, array $conditions): int
  331. {
  332. $query = DB::table($tableName);
  333. if (!empty($conditions['user_field']) && !empty($conditions['user_ids'])) {
  334. $userField = $conditions['user_field'];
  335. $userIds = is_array($conditions['user_ids']) ? $conditions['user_ids'] : [$conditions['user_ids']];
  336. $query->whereIn($userField, $userIds);
  337. }
  338. return $query->count();
  339. }
  340. /**
  341. * 按自定义条件统计记录数
  342. *
  343. * @param string $tableName 表名
  344. * @param array $conditions 条件
  345. * @return int 记录数
  346. */
  347. private static function countByCustomCondition(string $tableName, array $conditions): int
  348. {
  349. $query = DB::table($tableName);
  350. if (!empty($conditions['where'])) {
  351. foreach ($conditions['where'] as $condition) {
  352. if (isset($condition['field'], $condition['operator'], $condition['value'])) {
  353. $query->where($condition['field'], $condition['operator'], $condition['value']);
  354. }
  355. }
  356. }
  357. return $query->count();
  358. }
  359. /**
  360. * 检查Model是否支持软删除
  361. *
  362. * @param Model $model Model实例
  363. * @return bool 是否支持软删除
  364. */
  365. private static function modelSupportsSoftDeletes(Model $model): bool
  366. {
  367. return in_array(SoftDeletes::class, class_uses_recursive($model));
  368. }
  369. /**
  370. * 解析时间条件
  371. *
  372. * @param string $timeCondition 时间条件
  373. * @return string 解析后的时间
  374. */
  375. private static function parseTimeCondition(string $timeCondition): string
  376. {
  377. // 支持格式:30_days_ago, 1_month_ago, 2024-01-01, 等
  378. if (preg_match('/(\d+)_days?_ago/', $timeCondition, $matches)) {
  379. return now()->subDays((int)$matches[1])->toDateTimeString();
  380. }
  381. if (preg_match('/(\d+)_months?_ago/', $timeCondition, $matches)) {
  382. return now()->subMonths((int)$matches[1])->toDateTimeString();
  383. }
  384. if (preg_match('/(\d+)_years?_ago/', $timeCondition, $matches)) {
  385. return now()->subYears((int)$matches[1])->toDateTimeString();
  386. }
  387. // 直接返回时间字符串
  388. return $timeCondition;
  389. }
  390. /**
  391. * 估算执行时间
  392. *
  393. * @param int $totalRecords 总记录数
  394. * @return string 估算时间
  395. */
  396. private static function estimateExecutionTime(int $totalRecords): string
  397. {
  398. // 简单估算:每秒处理1000条记录
  399. $seconds = ceil($totalRecords / 1000);
  400. if ($seconds < 60) {
  401. return "{$seconds}秒";
  402. } elseif ($seconds < 3600) {
  403. $minutes = ceil($seconds / 60);
  404. return "{$minutes}分钟";
  405. } else {
  406. $hours = ceil($seconds / 3600);
  407. return "{$hours}小时";
  408. }
  409. }
  410. /**
  411. * 执行清理(支持Model类和表名两种模式)
  412. *
  413. * @param CleanupPlanContent $content 计划内容
  414. * @param int $taskId 任务ID
  415. * @return array 执行结果
  416. */
  417. private static function executeCleanup(CleanupPlanContent $content, int $taskId): array
  418. {
  419. $startTime = microtime(true);
  420. $cleanupType = CLEANUP_TYPE::from($content->cleanup_type);
  421. try {
  422. // 优先使用Model类,如果没有则使用表名
  423. if (!empty($content->model_class)) {
  424. return static::executeModelCleanup($content, $taskId, $startTime);
  425. } else {
  426. return static::executeTableCleanup($content, $taskId, $startTime);
  427. }
  428. } catch (\Exception $e) {
  429. $executionTime = round(microtime(true) - $startTime, 3);
  430. $targetName = $content->model_class ?: $content->table_name;
  431. // 记录错误日志
  432. static::logCleanupOperation($taskId, $content, $cleanupType, [
  433. 'error' => $e->getMessage(),
  434. 'execution_time' => $executionTime,
  435. 'conditions' => $content->conditions,
  436. ]);
  437. return [
  438. 'success' => false,
  439. 'message' => $e->getMessage(),
  440. 'deleted_records' => 0,
  441. 'execution_time' => $executionTime,
  442. ];
  443. }
  444. }
  445. /**
  446. * 执行基于Model类的清理
  447. *
  448. * @param CleanupPlanContent $content 计划内容
  449. * @param int $taskId 任务ID
  450. * @param float $startTime 开始时间
  451. * @return array 执行结果
  452. */
  453. private static function executeModelCleanup(CleanupPlanContent $content, int $taskId, float $startTime): array
  454. {
  455. $modelClass = $content->model_class;
  456. $cleanupType = CLEANUP_TYPE::from($content->cleanup_type);
  457. // 检查Model类是否存在
  458. if (!class_exists($modelClass)) {
  459. throw new \Exception("Model类不存在: {$modelClass}");
  460. }
  461. $model = new $modelClass();
  462. $tableName = $model->getTable();
  463. // 记录清理前的记录数
  464. $beforeCount = $modelClass::count();
  465. // 执行清理
  466. $deletedRecords = static::performModelCleanup($modelClass, $cleanupType, $content->conditions, $content->batch_size);
  467. // 记录清理后的记录数
  468. $afterCount = $modelClass::count();
  469. $actualDeleted = $beforeCount - $afterCount;
  470. $executionTime = round(microtime(true) - $startTime, 3);
  471. // 记录清理日志
  472. static::logCleanupOperation($taskId, $content, $cleanupType, [
  473. 'before_count' => $beforeCount,
  474. 'after_count' => $afterCount,
  475. 'deleted_records' => $actualDeleted,
  476. 'execution_time' => $executionTime,
  477. 'conditions' => $content->conditions,
  478. 'batch_size' => $content->batch_size,
  479. ]);
  480. return [
  481. 'success' => true,
  482. 'message' => "Model {$modelClass} 清理成功",
  483. 'deleted_records' => $actualDeleted,
  484. 'execution_time' => $executionTime,
  485. ];
  486. }
  487. /**
  488. * 执行基于表名的清理(向后兼容)
  489. *
  490. * @param CleanupPlanContent $content 计划内容
  491. * @param int $taskId 任务ID
  492. * @param float $startTime 开始时间
  493. * @return array 执行结果
  494. */
  495. private static function executeTableCleanup(CleanupPlanContent $content, int $taskId, float $startTime): array
  496. {
  497. $tableName = $content->table_name;
  498. $cleanupType = CLEANUP_TYPE::from($content->cleanup_type);
  499. // 检查表是否存在
  500. if (!Schema::hasTable($tableName)) {
  501. throw new \Exception("表 {$tableName} 不存在");
  502. }
  503. // 记录清理前的记录数
  504. $beforeCount = DB::table($tableName)->count();
  505. // 执行清理
  506. $deletedRecords = static::performTableCleanup($tableName, $cleanupType, $content->conditions, $content->batch_size);
  507. // 记录清理后的记录数
  508. $afterCount = DB::table($tableName)->count();
  509. $actualDeleted = $beforeCount - $afterCount;
  510. $executionTime = round(microtime(true) - $startTime, 3);
  511. // 记录清理日志
  512. static::logCleanupOperation($taskId, $content, $cleanupType, [
  513. 'before_count' => $beforeCount,
  514. 'after_count' => $afterCount,
  515. 'deleted_records' => $actualDeleted,
  516. 'execution_time' => $executionTime,
  517. 'conditions' => $content->conditions,
  518. 'batch_size' => $content->batch_size,
  519. ]);
  520. return [
  521. 'success' => true,
  522. 'message' => "表 {$tableName} 清理成功",
  523. 'deleted_records' => $actualDeleted,
  524. 'execution_time' => $executionTime,
  525. ];
  526. }
  527. /**
  528. * 执行基于Model类的清理操作
  529. *
  530. * @param string $modelClass Model类名
  531. * @param CLEANUP_TYPE $cleanupType 清理类型
  532. * @param array $conditions 清理条件
  533. * @param int $batchSize 批处理大小
  534. * @return int 删除的记录数
  535. */
  536. private static function performModelCleanup(string $modelClass, CLEANUP_TYPE $cleanupType, array $conditions, int $batchSize): int
  537. {
  538. switch ($cleanupType) {
  539. case CLEANUP_TYPE::TRUNCATE:
  540. return static::performModelTruncate($modelClass);
  541. case CLEANUP_TYPE::DELETE_ALL:
  542. return static::performModelDeleteAll($modelClass, $batchSize);
  543. case CLEANUP_TYPE::DELETE_BY_TIME:
  544. return static::performModelDeleteByTime($modelClass, $conditions, $batchSize);
  545. case CLEANUP_TYPE::DELETE_BY_USER:
  546. return static::performModelDeleteByUser($modelClass, $conditions, $batchSize);
  547. case CLEANUP_TYPE::DELETE_BY_CONDITION:
  548. return static::performModelDeleteByCondition($modelClass, $conditions, $batchSize);
  549. default:
  550. throw new \Exception("不支持的清理类型: {$cleanupType->value}");
  551. }
  552. }
  553. /**
  554. * 执行基于表名的清理操作(向后兼容)
  555. *
  556. * @param string $tableName 表名
  557. * @param CLEANUP_TYPE $cleanupType 清理类型
  558. * @param array $conditions 清理条件
  559. * @param int $batchSize 批处理大小
  560. * @return int 删除的记录数
  561. */
  562. private static function performTableCleanup(string $tableName, CLEANUP_TYPE $cleanupType, array $conditions, int $batchSize): int
  563. {
  564. switch ($cleanupType) {
  565. case CLEANUP_TYPE::TRUNCATE:
  566. return static::performTableTruncate($tableName);
  567. case CLEANUP_TYPE::DELETE_ALL:
  568. return static::performTableDeleteAll($tableName, $batchSize);
  569. case CLEANUP_TYPE::DELETE_BY_TIME:
  570. return static::performTableDeleteByTime($tableName, $conditions, $batchSize);
  571. case CLEANUP_TYPE::DELETE_BY_USER:
  572. return static::performTableDeleteByUser($tableName, $conditions, $batchSize);
  573. case CLEANUP_TYPE::DELETE_BY_CONDITION:
  574. return static::performTableDeleteByCondition($tableName, $conditions, $batchSize);
  575. default:
  576. throw new \Exception("不支持的清理类型: {$cleanupType->value}");
  577. }
  578. }
  579. /**
  580. * 执行Model的TRUNCATE操作
  581. *
  582. * @param string $modelClass Model类名
  583. * @return int 删除的记录数
  584. */
  585. private static function performModelTruncate(string $modelClass): int
  586. {
  587. $beforeCount = $modelClass::count();
  588. $modelClass::truncate();
  589. return $beforeCount;
  590. }
  591. /**
  592. * 执行表的TRUNCATE操作(向后兼容)
  593. *
  594. * @param string $tableName 表名
  595. * @return int 删除的记录数
  596. */
  597. private static function performTableTruncate(string $tableName): int
  598. {
  599. $beforeCount = DB::table($tableName)->count();
  600. DB::statement("TRUNCATE TABLE `{$tableName}`");
  601. return $beforeCount;
  602. }
  603. /**
  604. * 执行Model的DELETE ALL操作
  605. *
  606. * @param string $modelClass Model类名
  607. * @param int $batchSize 批处理大小
  608. * @return int 删除的记录数
  609. */
  610. private static function performModelDeleteAll(string $modelClass, int $batchSize): int
  611. {
  612. $totalDeleted = 0;
  613. do {
  614. $deleted = $modelClass::limit($batchSize)->delete();
  615. $totalDeleted += $deleted;
  616. } while ($deleted > 0);
  617. return $totalDeleted;
  618. }
  619. /**
  620. * 执行表的DELETE ALL操作(向后兼容)
  621. *
  622. * @param string $tableName 表名
  623. * @param int $batchSize 批处理大小
  624. * @return int 删除的记录数
  625. */
  626. private static function performTableDeleteAll(string $tableName, int $batchSize): int
  627. {
  628. $totalDeleted = 0;
  629. do {
  630. $deleted = DB::table($tableName)->limit($batchSize)->delete();
  631. $totalDeleted += $deleted;
  632. } while ($deleted > 0);
  633. return $totalDeleted;
  634. }
  635. /**
  636. * 执行Model的按时间删除操作
  637. *
  638. * @param string $modelClass Model类名
  639. * @param array $conditions 条件
  640. * @param int $batchSize 批处理大小
  641. * @return int 删除的记录数
  642. */
  643. private static function performModelDeleteByTime(string $modelClass, array $conditions, int $batchSize): int
  644. {
  645. if (empty($conditions['time_field']) || empty($conditions['before'])) {
  646. throw new \Exception('时间删除条件不完整');
  647. }
  648. $timeField = $conditions['time_field'];
  649. $beforeTime = static::parseTimeCondition($conditions['before']);
  650. $totalDeleted = 0;
  651. // 检查Model是否支持软删除
  652. $model = new $modelClass();
  653. $supportsSoftDeletes = static::modelSupportsSoftDeletes($model);
  654. $forceDelete = $conditions['force_delete'] ?? false;
  655. do {
  656. $query = $modelClass::where($timeField, '<', $beforeTime)->limit($batchSize);
  657. if ($supportsSoftDeletes && $forceDelete) {
  658. $deleted = $query->forceDelete();
  659. } else {
  660. $deleted = $query->delete();
  661. }
  662. $totalDeleted += $deleted;
  663. } while ($deleted > 0);
  664. return $totalDeleted;
  665. }
  666. /**
  667. * 执行表的按时间删除操作(向后兼容)
  668. *
  669. * @param string $tableName 表名
  670. * @param array $conditions 条件
  671. * @param int $batchSize 批处理大小
  672. * @return int 删除的记录数
  673. */
  674. private static function performTableDeleteByTime(string $tableName, array $conditions, int $batchSize): int
  675. {
  676. if (empty($conditions['time_field']) || empty($conditions['before'])) {
  677. throw new \Exception('时间删除条件不完整');
  678. }
  679. $timeField = $conditions['time_field'];
  680. $beforeTime = static::parseTimeCondition($conditions['before']);
  681. $totalDeleted = 0;
  682. do {
  683. $deleted = DB::table($tableName)
  684. ->where($timeField, '<', $beforeTime)
  685. ->limit($batchSize)
  686. ->delete();
  687. $totalDeleted += $deleted;
  688. } while ($deleted > 0);
  689. return $totalDeleted;
  690. }
  691. /**
  692. * 执行Model的按用户删除操作
  693. *
  694. * @param string $modelClass Model类名
  695. * @param array $conditions 条件
  696. * @param int $batchSize 批处理大小
  697. * @return int 删除的记录数
  698. */
  699. private static function performModelDeleteByUser(string $modelClass, array $conditions, int $batchSize): int
  700. {
  701. if (empty($conditions['user_field']) || empty($conditions['user_values'])) {
  702. throw new \Exception('用户删除条件不完整');
  703. }
  704. $userField = $conditions['user_field'];
  705. $userCondition = $conditions['user_condition'] ?? 'in';
  706. $userValues = is_array($conditions['user_values']) ? $conditions['user_values'] : [$conditions['user_values']];
  707. $totalDeleted = 0;
  708. // 检查Model是否支持软删除
  709. $model = new $modelClass();
  710. $supportsSoftDeletes = static::modelSupportsSoftDeletes($model);
  711. $forceDelete = $conditions['force_delete'] ?? false;
  712. do {
  713. $query = $modelClass::query();
  714. // 应用用户条件
  715. switch ($userCondition) {
  716. case 'in':
  717. $query->whereIn($userField, $userValues);
  718. break;
  719. case 'not_in':
  720. $query->whereNotIn($userField, $userValues);
  721. break;
  722. case 'null':
  723. $query->whereNull($userField);
  724. break;
  725. case 'not_null':
  726. $query->whereNotNull($userField);
  727. break;
  728. default:
  729. throw new \Exception("不支持的用户条件: {$userCondition}");
  730. }
  731. $query->limit($batchSize);
  732. if ($supportsSoftDeletes && $forceDelete) {
  733. $deleted = $query->forceDelete();
  734. } else {
  735. $deleted = $query->delete();
  736. }
  737. $totalDeleted += $deleted;
  738. } while ($deleted > 0);
  739. return $totalDeleted;
  740. }
  741. /**
  742. * 执行表的按用户删除操作(向后兼容)
  743. *
  744. * @param string $tableName 表名
  745. * @param array $conditions 条件
  746. * @param int $batchSize 批处理大小
  747. * @return int 删除的记录数
  748. */
  749. private static function performTableDeleteByUser(string $tableName, array $conditions, int $batchSize): int
  750. {
  751. if (empty($conditions['user_field']) || empty($conditions['user_ids'])) {
  752. throw new \Exception('用户删除条件不完整');
  753. }
  754. $userField = $conditions['user_field'];
  755. $userIds = is_array($conditions['user_ids']) ? $conditions['user_ids'] : [$conditions['user_ids']];
  756. $totalDeleted = 0;
  757. do {
  758. $deleted = DB::table($tableName)
  759. ->whereIn($userField, $userIds)
  760. ->limit($batchSize)
  761. ->delete();
  762. $totalDeleted += $deleted;
  763. } while ($deleted > 0);
  764. return $totalDeleted;
  765. }
  766. /**
  767. * 执行Model的按条件删除操作
  768. *
  769. * @param string $modelClass Model类名
  770. * @param array $conditions 条件
  771. * @param int $batchSize 批处理大小
  772. * @return int 删除的记录数
  773. */
  774. private static function performModelDeleteByCondition(string $modelClass, array $conditions, int $batchSize): int
  775. {
  776. if (empty($conditions['where'])) {
  777. throw new \Exception('自定义删除条件不完整');
  778. }
  779. $totalDeleted = 0;
  780. // 检查Model是否支持软删除
  781. $model = new $modelClass();
  782. $supportsSoftDeletes = static::modelSupportsSoftDeletes($model);
  783. $forceDelete = $conditions['force_delete'] ?? false;
  784. do {
  785. $query = $modelClass::query();
  786. foreach ($conditions['where'] as $condition) {
  787. if (isset($condition['field'], $condition['operator'], $condition['value'])) {
  788. $query->where($condition['field'], $condition['operator'], $condition['value']);
  789. }
  790. }
  791. $query->limit($batchSize);
  792. if ($supportsSoftDeletes && $forceDelete) {
  793. $deleted = $query->forceDelete();
  794. } else {
  795. $deleted = $query->delete();
  796. }
  797. $totalDeleted += $deleted;
  798. } while ($deleted > 0);
  799. return $totalDeleted;
  800. }
  801. /**
  802. * 执行表的按条件删除操作(向后兼容)
  803. *
  804. * @param string $tableName 表名
  805. * @param array $conditions 条件
  806. * @param int $batchSize 批处理大小
  807. * @return int 删除的记录数
  808. */
  809. private static function performTableDeleteByCondition(string $tableName, array $conditions, int $batchSize): int
  810. {
  811. if (empty($conditions['where'])) {
  812. throw new \Exception('自定义删除条件不完整');
  813. }
  814. $totalDeleted = 0;
  815. do {
  816. $query = DB::table($tableName);
  817. foreach ($conditions['where'] as $condition) {
  818. if (isset($condition['field'], $condition['operator'], $condition['value'])) {
  819. $query->where($condition['field'], $condition['operator'], $condition['value']);
  820. }
  821. }
  822. $deleted = $query->limit($batchSize)->delete();
  823. $totalDeleted += $deleted;
  824. } while ($deleted > 0);
  825. return $totalDeleted;
  826. }
  827. /**
  828. * 记录清理操作日志
  829. *
  830. * @param int $taskId 任务ID
  831. * @param CleanupPlanContent $content 计划内容
  832. * @param CLEANUP_TYPE $cleanupType 清理类型
  833. * @param array $details 详细信息
  834. */
  835. private static function logCleanupOperation(int $taskId, CleanupPlanContent $content, CLEANUP_TYPE $cleanupType, array $details): void
  836. {
  837. try {
  838. $tableName = $content->table_name;
  839. if (!empty($content->model_class)) {
  840. // 如果有Model类,从Model获取表名
  841. $modelClass = $content->model_class;
  842. if (class_exists($modelClass)) {
  843. $model = new $modelClass();
  844. $tableName = $model->getTable();
  845. }
  846. }
  847. CleanupLog::create([
  848. 'task_id' => $taskId,
  849. 'table_name' => $tableName,
  850. 'cleanup_type' => $cleanupType->value,
  851. 'before_count' => $details['before_count'] ?? 0,
  852. 'after_count' => $details['after_count'] ?? 0,
  853. 'deleted_records' => $details['deleted_records'] ?? 0,
  854. 'execution_time' => $details['execution_time'] ?? 0,
  855. 'conditions' => $details['conditions'] ?? [],
  856. 'error_message' => $details['error'] ?? null,
  857. 'model_class' => $content->model_class,
  858. 'created_at' => now(),
  859. ]);
  860. } catch (\Exception $e) {
  861. Log::error('记录清理日志失败', [
  862. 'task_id' => $taskId,
  863. 'model_class' => $content->model_class ?? null,
  864. 'table_name' => $content->table_name ?? null,
  865. 'error' => $e->getMessage()
  866. ]);
  867. }
  868. }
  869. }