This commit is contained in:
gs committed 2026-09-25 22:08:37 +08:00
1 parent 01f9f2c514
commit dc23ea53ed
25 files changed
+3116 -176

No files matched your search

+95
View File
@@ -9,11 +9,79 @@ const pool = mysql.createPool({
database: process.env.DB_NAME || 'yyyy',
waitForConnections: true,
connectionLimit: 10,
maxIdle: 2,
idleTimeout: 30000,
enableKeepAlive: true,
keepAliveInitialDelay: 5000,
queueLimit: 0,
connectTimeout: 10000,
dateStrings: true
});
// 监听底层连接错误,防止空闲断开的 Socket 触发未捕获异常
if (pool.pool) {
pool.pool.on('connection', (connection) => {
connection.on('error', (err) => {
if (err.code === 'PROTOCOL_CONNECTION_LOST' || err.code === 'ECONNRESET') {
console.warn('[DB] Stale connection dropped by remote server, pool will reconnect.');
} else {
console.error('[DB] Connection error:', err.message);
}
});
});
}
// 封装带自动重试的 query 与 execute,抵御云端 MySQL/NAT 偶发断连
const originalQuery = pool.query.bind(pool);
const originalExecute = pool.execute.bind(pool);
async function executeWithRetry(fn, args, maxRetries = 3) {
let attempt = 0;
while (true) {
try {
return await fn(...args);
} catch (err) {
attempt++;
const isConnectionLost = err && (
err.code === 'PROTOCOL_CONNECTION_LOST' ||
err.code === 'ECONNRESET' ||
err.code === 'ETIMEDOUT' ||
err.code === 'EPIPE' ||
err.code === 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR' ||
err.fatal
);
if (isConnectionLost && attempt <= maxRetries) {
console.warn(`[DB] MySQL connection lost (${err.code || err.message}). Auto-retrying attempt ${attempt}/${maxRetries}...`);
await new Promise(res => setTimeout(res, 250 * attempt));
continue;
}
throw err;
}
}
}
pool.query = function(...args) {
return executeWithRetry(originalQuery, args);
};
pool.execute = function(...args) {
return executeWithRetry(originalExecute, args);
};
// 心跳探针:每 25 秒自动执行一次 SELECT 1,防止云端防火墙丢弃空闲长连接
const heartbeatTimer = setInterval(async () => {
try {
await pool.query('SELECT 1');
} catch (err) {
console.warn('[DB] Heartbeat ping error:', err.message);
}
}, 25000);
if (heartbeatTimer.unref) {
heartbeatTimer.unref();
}
/**
* 数据库初始化
*
@@ -135,6 +203,33 @@ async function initDatabase() {
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='看护人用户表(预留)';
`);
// 7. 家庭日常备忘待办清单表 (family_memo - 家庭看护团队协同清单)
await conn.query(`
CREATE TABLE IF NOT EXISTS \`family_memo\` (
\`id\` BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '自增主键',
\`memo_id\` VARCHAR(64) NOT NULL UNIQUE COMMENT '备忘唯一业务ID',
\`family_id\` VARCHAR(64) NOT NULL DEFAULT 'family-001' COMMENT '所属家庭ID',
\`content\` VARCHAR(255) NOT NULL COMMENT '待办备忘内容',
\`due_period\` VARCHAR(30) DEFAULT 'today' COMMENT '推荐时段',
\`is_completed\` TINYINT(1) DEFAULT 0 COMMENT '是否已完成',
\`completed_at\` DATETIME NULL COMMENT '完成时刻',
\`created_by\` VARCHAR(50) DEFAULT '宝妈' COMMENT '创建人称谓',
\`created_at\` DATETIME DEFAULT CURRENT_TIMESTAMP,
\`updated_at\` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX \`idx_memo_family\` (\`family_id\`, \`is_completed\`),
INDEX \`idx_memo_created\` (\`created_at\`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='家庭日常备忘待办清单表';
`);
// 增量字段安全检测 (preferences & default_config)
try {
await conn.query("ALTER TABLE `family_member` ADD COLUMN `preferences` JSON NULL COMMENT '角色专属行为偏好'");
} catch (e) {}
try {
await conn.query("ALTER TABLE `baby_profile` ADD COLUMN `default_config` JSON NULL COMMENT '宝宝默认行为配置'");
} catch (e) {}
// 预置默认家庭 (如果无家庭)
const [existingFamilies] = await conn.query('SELECT COUNT(*) as count FROM `family`');
if (existingFamilies[0].count === 0) {