SaltController.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. <?php
  2. namespace console\controllers;
  3. use bizGhs\order\models\Order as GhsOrder;
  4. use bizHd\purchase\models\Purchase;
  5. use common\components\stringUtil;
  6. use Yii;
  7. use yii\console\Controller;
  8. use yii\console\ExitCode;
  9. /**
  10. * 补充历史订单 salt 字段
  11. *
  12. * 大表安全说明:
  13. * - 不做 COUNT(*),避免全表统计
  14. * - 默认 empty 模式只查 salt='' 的记录,补完后即停止,不会扫全表
  15. * - 查询均为普通 SELECT(MVCC 快照读),不会锁表;UPDATE 仅锁单行
  16. * - 大表建议先加索引: ALTER TABLE xhGhsOrder ADD INDEX idx_salt_id (salt, id);
  17. *
  18. * 用法:
  19. * php yii salt/fill
  20. * php yii salt/fill --dryRun=1
  21. * php yii salt/fill --batchSize=1000 --sleepMs=200
  22. * php yii salt/fill --mode=pk --scanSize=1000
  23. * php yii salt/fill-ghs-order
  24. * php yii salt/fill-cg
  25. * php yii salt/fill-clear
  26. * php yii salt/fill-settle
  27. */
  28. class SaltController extends Controller
  29. {
  30. /** @var int 每批处理条数 */
  31. public $batchSize = 1000;
  32. /** @var int pk 模式下每次主键游标扫描行数 */
  33. public $scanSize = 1000;
  34. /**
  35. * 扫描模式:
  36. * - empty: 只查 salt='',适合待补数据量较少(默认)
  37. * - pk: 按主键分段扫描,适合 salt 列无索引且 empty 模式执行计划不佳时
  38. */
  39. public $mode = 'empty';
  40. /** @var int 每批之间的休眠毫秒数,降低白天执行时的数据库压力 */
  41. public $sleepMs = 100;
  42. /** @var int 最多处理条数,0 表示全部 */
  43. public $limit = 0;
  44. /** @var int 是否仅预览,1=是 */
  45. public $dryRun = 0;
  46. public function options($actionID)
  47. {
  48. return array_merge(parent::options($actionID), [
  49. 'batchSize',
  50. 'scanSize',
  51. 'mode',
  52. 'sleepMs',
  53. 'limit',
  54. 'dryRun',
  55. ]);
  56. }
  57. /**
  58. * 补充 xhGhsOrder、xhCg 历史数据的 salt 字段
  59. */
  60. public function actionFill()
  61. {
  62. return $this->runFill([
  63. 'xhGhsOrder' => GhsOrder::tableName(),
  64. 'xhCg' => Purchase::tableName(),
  65. ]);
  66. }
  67. /**
  68. * 仅补充 xhGhsOrder
  69. */
  70. public function actionFillGhsOrder()
  71. {
  72. return $this->runFill([
  73. 'xhGhsOrder' => GhsOrder::tableName(),
  74. ]);
  75. }
  76. /**
  77. * 仅补充 xhCg
  78. */
  79. public function actionFillCg()
  80. {
  81. return $this->runFill([
  82. 'xhCg' => Purchase::tableName(),
  83. ]);
  84. }
  85. /**
  86. * 补充 xhClear 结账单历史数据的 salt 字段
  87. * 职责:查询全部 xhClear 记录,循环重新生成并设置 salt
  88. */
  89. public function actionFillClear()
  90. {
  91. $db = Yii::$app->db;
  92. // 查询全部结账单 ID
  93. $ids = $db->createCommand("SELECT id FROM xhClear ORDER BY id DESC")->queryColumn();
  94. $count = 0;
  95. foreach ($ids as $id) {
  96. if ($this->dryRun) {
  97. $this->stdout("[dry-run] xhClear id={$id}\n");
  98. $count++;
  99. continue;
  100. }
  101. // 重新生成 10 位随机 salt 并更新
  102. $salt = stringUtil::charsShuffleLowerCase(10);
  103. $db->createCommand("UPDATE xhClear SET salt = :salt WHERE id = :id")
  104. ->bindValues([':salt' => $salt, ':id' => $id])
  105. ->execute();
  106. $count++;
  107. }
  108. $this->stdout("xhClear salt 全部重新设置完成,共处理 {$count} 条记录\n");
  109. return ExitCode::OK;
  110. }
  111. /**
  112. * 补充 xhSettle 结算单历史数据的 salt 字段
  113. * 职责:查询全部 xhSettle 记录,循环重新生成并设置 salt
  114. */
  115. public function actionFillSettle()
  116. {
  117. $db = Yii::$app->db;
  118. // 查询全部结算单 ID
  119. $ids = $db->createCommand("SELECT id FROM xhSettle ORDER BY id DESC")->queryColumn();
  120. $count = 0;
  121. foreach ($ids as $id) {
  122. if ($this->dryRun) {
  123. $this->stdout("[dry-run] xhSettle id={$id}\n");
  124. $count++;
  125. continue;
  126. }
  127. // 重新生成 10 位随机 salt 并更新
  128. $salt = stringUtil::charsShuffleLowerCase(10);
  129. $db->createCommand("UPDATE xhSettle SET salt = :salt WHERE id = :id")
  130. ->bindValues([':salt' => $salt, ':id' => $id])
  131. ->execute();
  132. $count++;
  133. }
  134. $this->stdout("xhSettle salt 全部重新设置完成,共处理 {$count} 条记录\n");
  135. return ExitCode::OK;
  136. }
  137. private function runFill(array $tables)
  138. {
  139. ini_set('memory_limit', '512M');
  140. set_time_limit(0);
  141. if ($this->batchSize < 1) {
  142. $this->stderr("batchSize 必须大于 0\n");
  143. return ExitCode::UNSPECIFIED_ERROR;
  144. }
  145. if ($this->scanSize < 1) {
  146. $this->stderr("scanSize 必须大于 0\n");
  147. return ExitCode::UNSPECIFIED_ERROR;
  148. }
  149. if (!in_array($this->mode, ['empty', 'pk'], true)) {
  150. $this->stderr("mode 仅支持 empty 或 pk\n");
  151. return ExitCode::UNSPECIFIED_ERROR;
  152. }
  153. $exitCode = ExitCode::OK;
  154. foreach ($tables as $label => $tableName) {
  155. $code = $this->fillTable($label, $tableName);
  156. if ($code !== ExitCode::OK) {
  157. $exitCode = $code;
  158. }
  159. }
  160. return $exitCode;
  161. }
  162. private function fillTable($label, $tableName)
  163. {
  164. $db = Yii::$app->db;
  165. $db->createCommand('SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED')->execute();
  166. $this->stdout("{$label}({$tableName}) 开始补充 salt,模式: {$this->mode}\n");
  167. if ($this->mode === 'empty') {
  168. $processed = $this->fillByEmptySalt($label, $tableName);
  169. } else {
  170. $processed = $this->fillByPrimaryKeyScan($label, $tableName);
  171. }
  172. $this->stdout("{$label} 完成,本次处理 {$processed} 条\n");
  173. return ExitCode::OK;
  174. }
  175. /**
  176. * 只查 salt='' 的记录,从最大 id 向小 id 分批处理
  177. */
  178. private function fillByEmptySalt($label, $tableName)
  179. {
  180. $db = Yii::$app->db;
  181. $processed = 0;
  182. $lastId = null;
  183. while (true) {
  184. if ($this->limit > 0 && $processed >= $this->limit) {
  185. break;
  186. }
  187. $batchLimit = $this->limit > 0 ? min($this->batchSize, $this->limit - $processed) : $this->batchSize;
  188. if ($lastId === null) {
  189. $rows = $db->createCommand(
  190. "SELECT id FROM {$tableName} WHERE salt = '' ORDER BY id DESC LIMIT {$batchLimit}"
  191. )->queryColumn();
  192. } else {
  193. $rows = $db->createCommand(
  194. "SELECT id FROM {$tableName} WHERE salt = '' AND id < :lastId ORDER BY id DESC LIMIT {$batchLimit}"
  195. )->bindValue(':lastId', $lastId)->queryColumn();
  196. }
  197. if (empty($rows)) {
  198. break;
  199. }
  200. $processed += $this->updateIds($label, $tableName, $rows);
  201. $lastId = (int)min($rows);
  202. $this->stdout("{$label} 已处理 {$processed} 条,当前 id >= {$lastId}\n");
  203. $this->sleepBetweenBatch();
  204. }
  205. return $processed;
  206. }
  207. /**
  208. * 按主键从最大 id 向小 id 分段扫描;适合 empty 模式执行计划不佳时使用
  209. */
  210. private function fillByPrimaryKeyScan($label, $tableName)
  211. {
  212. $db = Yii::$app->db;
  213. $processed = 0;
  214. $lastId = null;
  215. while (true) {
  216. if ($this->limit > 0 && $processed >= $this->limit) {
  217. break;
  218. }
  219. if ($lastId === null) {
  220. $ids = $db->createCommand(
  221. "SELECT id FROM {$tableName} ORDER BY id DESC LIMIT {$this->scanSize}"
  222. )->queryColumn();
  223. } else {
  224. $ids = $db->createCommand(
  225. "SELECT id FROM {$tableName} WHERE id < :lastId ORDER BY id DESC LIMIT {$this->scanSize}"
  226. )->bindValue(':lastId', $lastId)->queryColumn();
  227. }
  228. if (empty($ids)) {
  229. break;
  230. }
  231. $lastId = (int)min($ids);
  232. $minId = (int)min($ids);
  233. $maxId = (int)max($ids);
  234. $emptyIds = $db->createCommand(
  235. "SELECT id FROM {$tableName} WHERE id >= :minId AND id <= :maxId AND salt = '' ORDER BY id DESC"
  236. )->bindValues([
  237. ':minId' => $minId,
  238. ':maxId' => $maxId,
  239. ])->queryColumn();
  240. if (!empty($emptyIds)) {
  241. if ($this->limit > 0) {
  242. $emptyIds = array_slice($emptyIds, 0, $this->limit - $processed);
  243. }
  244. $processed += $this->updateIds($label, $tableName, $emptyIds);
  245. }
  246. $this->stdout("{$label} 已处理 {$processed} 条,已扫描到 id >= {$lastId}\n");
  247. $this->sleepBetweenBatch();
  248. }
  249. return $processed;
  250. }
  251. private function updateIds($label, $tableName, array $ids)
  252. {
  253. $db = Yii::$app->db;
  254. $updated = 0;
  255. foreach ($ids as $id) {
  256. $id = (int)$id;
  257. if ($id <= 0) {
  258. continue;
  259. }
  260. if ($this->dryRun) {
  261. $this->stdout("[dry-run] {$label} id={$id}\n");
  262. $updated++;
  263. continue;
  264. }
  265. $salt = stringUtil::charsShuffleLowerCase(10);
  266. $affected = $db->createCommand(
  267. "UPDATE {$tableName} SET salt = :salt WHERE id = :id AND salt = ''"
  268. )->bindValues([
  269. ':salt' => $salt,
  270. ':id' => $id,
  271. ])->execute();
  272. if ($affected > 0) {
  273. $updated++;
  274. }
  275. }
  276. return $updated;
  277. }
  278. private function sleepBetweenBatch()
  279. {
  280. if ($this->sleepMs > 0) {
  281. usleep($this->sleepMs * 1000);
  282. }
  283. }
  284. }