You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

109 lines
3.8 KiB

// 测试脚本:验证聊天消息处理中的userId类型不匹配问题
const mysql = require('mysql2/promise');
// 数据库连接配置
const config = {
host: '1.95.162.61',
port: 3306,
user: 'root',
password: 'schl@2025',
database: 'wechat_app'
};
async function testMessageProcessing() {
let connection;
try {
// 连接数据库
connection = await mysql.createConnection(config);
console.log('数据库连接成功');
// 测试1:验证userId类型不匹配问题
const testUserId = 'user_1765610275027_qqkb12ws3'; // 字符串类型
const testManagerId = '22'; // 客服ID
console.log('\n=== 测试场景:模拟用户发送消息 ===');
console.log(`用户ID (字符串): ${testUserId}`);
console.log(`客服ID: ${testManagerId}`);
// 尝试创建会话,模拟实际场景中的类型转换问题
console.log('\n尝试创建会话(模拟应用逻辑):');
try {
// 这里模拟应用中尝试将字符串userId存入int字段的场景
const [result] = await connection.execute(
'INSERT INTO chat_conversations (conversation_id, userId, managerId, status) VALUES (UUID(), ?, ?, 1)',
[testUserId, testManagerId]
);
console.log('✓ 会话创建成功');
} catch (error) {
console.error('❌ 会话创建失败:', error.message);
console.log('这验证了userId类型不匹配的问题:字符串类型的userId无法存入int字段');
}
// 测试2:检查数据库中的现有数据
console.log('\n=== 检查数据库中的现有数据 ===');
// 检查用户是否存在
const [users] = await connection.execute(
'SELECT userId, nickName, avatarUrl FROM users WHERE userId = ?',
[testUserId]
);
if (users.length > 0) {
console.log('✓ 用户存在于users表中:');
console.log(` userId: ${users[0].userId} (类型: ${typeof users[0].userId})`);
console.log(` nickName: ${users[0].nickName}`);
} else {
console.log('❌ 用户不存在于users表中');
}
// 检查是否存在相关会话
const [conversations] = await connection.execute(
'SELECT * FROM chat_conversations WHERE userId = ? OR managerId = ?',
[testUserId, testManagerId]
);
console.log(`\n会话数量: ${conversations.length}`);
if (conversations.length > 0) {
console.log('现有会话信息:');
conversations.forEach((conv, index) => {
console.log(` 会话 ${index + 1}:`);
console.log(` conversation_id: ${conv.conversation_id}`);
console.log(` userId: ${conv.userId} (类型: ${typeof conv.userId})`);
console.log(` managerId: ${conv.managerId}`);
console.log(` status: ${conv.status}`);
});
}
// 测试3:验证类型转换对查询的影响
console.log('\n=== 测试类型转换对查询的影响 ===');
// 尝试使用字符串userId查询
const [stringQuery] = await connection.execute(
'SELECT * FROM chat_conversations WHERE userId = ?',
[testUserId]
);
console.log(`使用字符串userId查询结果数: ${stringQuery.length}`);
// 尝试转换为数字后查询(这会导致丢失非数字前缀)
const numericId = parseInt(testUserId);
console.log(`userId转换为数字: ${numericId} (从原始字符串: ${testUserId})`);
const [numericQuery] = await connection.execute(
'SELECT * FROM chat_conversations WHERE userId = ?',
[numericId]
);
console.log(`使用数字userId查询结果数: ${numericQuery.length}`);
} catch (error) {
console.error('测试过程中发生错误:', error);
} finally {
if (connection) {
await connection.end();
console.log('\n数据库连接已关闭');
}
}
}
// 运行测试
testMessageProcessing();