This commit is contained in:
张成
2025-12-19 13:24:12 +08:00
parent 34ebad316a
commit eca314e686
3 changed files with 106 additions and 61 deletions

View File

@@ -243,13 +243,18 @@ class PlaAccountService {
}
// 通过 sn_code 查询任务列表
// 使用 attributes 只查询需要的字段,提升性能
const result = await task_status.findAndCountAll({
where: {
sn_code: account.sn_code
},
limit,
offset,
order: [['id', 'DESC']]
order: [['id', 'DESC']],
// 不查询大字段以提升性能
attributes: {
exclude: ['taskParams', 'result', 'errorMessage', 'errorStack']
}
});
// 将 Sequelize 模型实例转换为普通对象
@@ -271,7 +276,6 @@ class PlaAccountService {
const task_commands = db.getModel('task_commands');
const task_status = db.getModel('task_status');
const Sequelize = require('sequelize');
const Op = Sequelize.Op;
const { id, limit, offset } = params;
@@ -285,44 +289,50 @@ class PlaAccountService {
throw new Error('账号不存在');
}
// 先查询所有匹配 sn_code 的任务 ID
const tasks = await task_status.findAll({
where: {
sn_code: account.sn_code
},
attributes: ['id']
});
// 使用子查询优化性能,避免先查询所有任务ID
const sequelize = task_commands.sequelize;
// 使用子查询一次性完成查询和计数
const countSql = `
SELECT COUNT(*) as count
FROM task_commands tc
WHERE tc.task_id IN (
SELECT id FROM task_status WHERE sn_code = :sn_code
)
`;
const taskIds = tasks.map(task => task.id);
const dataSql = `
SELECT tc.*,
tc.create_time
FROM task_commands tc
WHERE tc.task_id IN (
SELECT id FROM task_status WHERE sn_code = :sn_code
)
ORDER BY tc.id DESC
LIMIT :limit OFFSET :offset
`;
// 如果没有任务,直接返回空结果
if (taskIds.length === 0) {
return {
count: 0,
rows: []
};
}
// 并行执行查询和计数
const [countResult, dataResult] = await Promise.all([
sequelize.query(countSql, {
replacements: { sn_code: account.sn_code },
type: Sequelize.QueryTypes.SELECT
}),
sequelize.query(dataSql, {
replacements: {
sn_code: account.sn_code,
limit: limit,
offset: offset
},
type: Sequelize.QueryTypes.SELECT
})
]);
// 使用 Sequelize 模型查询指令列表
const result = await task_commands.findAndCountAll({
where: {
task_id: {
[Op.in]: taskIds
}
},
limit,
offset,
order: [['id', 'DESC']]
});
const count = countResult[0]?.count || 0;
// 将 Sequelize 模型实例转换为普通对象
const rows = result.rows.map(row => {
const plainRow = row.get({ plain: true });
// 添加 create_time 字段(使用 start_time 或 createdAt
if (!plainRow.create_time) {
plainRow.create_time = plainRow.start_time || plainRow.createdAt || null;
}
// 将原始数据转换为普通对象
const rows = dataResult.map(row => {
const plainRow = { ...row };
// 解析 JSON 字段
if (plainRow.command_params && typeof plainRow.command_params === 'string') {
@@ -344,7 +354,7 @@ class PlaAccountService {
});
return {
count: result.count,
count: parseInt(count),
rows: rows
};
}