puzhibing
2026-09-02 bf82d9f70479a5ea99ff2ea00b35cb3b6b7d500f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
-- Add VIN snapshot column to every physical charging-order shard.
-- Execute directly on the backend MySQL instance, not through the database proxy.
-- The procedure is idempotent and only alters existing tables that lack the column.
 
USE `charging_pile_order`;
 
DROP PROCEDURE IF EXISTS `add_charging_order_vin`;
DELIMITER $$
CREATE PROCEDURE `add_charging_order_vin`()
BEGIN
    DECLARE shard_no INT DEFAULT 0;
    DECLARE target_table VARCHAR(64);
    DECLARE table_exists INT DEFAULT 0;
    DECLARE column_exists INT DEFAULT 0;
 
    WHILE shard_no < 50 DO
        SET target_table = CONCAT('t_charging_order_', shard_no);
 
        SELECT COUNT(*) INTO table_exists
        FROM information_schema.tables
        WHERE table_schema = DATABASE()
          AND table_name = target_table;
 
        SELECT COUNT(*) INTO column_exists
        FROM information_schema.columns
        WHERE table_schema = DATABASE()
          AND table_name = target_table
          AND column_name = 'vin';
 
        IF table_exists = 1 AND column_exists = 0 THEN
            SET @ddl = CONCAT(
                'ALTER TABLE `', target_table,
                '` ADD COLUMN `vin` varchar(17) NULL AFTER `reservation_time`'
            );
            PREPARE stmt FROM @ddl;
            EXECUTE stmt;
            DEALLOCATE PREPARE stmt;
        END IF;
 
        SET shard_no = shard_no + 1;
    END WHILE;
END$$
DELIMITER ;
 
CALL `add_charging_order_vin`();
DROP PROCEDURE `add_charging_order_vin`;
 
SELECT COUNT(*) AS shard_count,
       SUM(CASE WHEN c.column_name = 'vin' THEN 1 ELSE 0 END) AS vin_column_count
FROM information_schema.tables t
LEFT JOIN information_schema.columns c
       ON c.table_schema = t.table_schema
      AND c.table_name = t.table_name
      AND c.column_name = 'vin'
WHERE t.table_schema = DATABASE()
  AND t.table_name REGEXP '^t_charging_order_[0-9]+$';