fix handler_org error use temporary table
All checks were successful
Build & Deploy on Dev / build (push) Successful in 1m7s

This commit is contained in:
Warunee Tamkoo 2026-05-01 00:22:16 +07:00
parent 7827e19254
commit ef279df452
2 changed files with 1378 additions and 1359 deletions

View file

@ -433,40 +433,53 @@ export async function BatchUpdatePosMasters(
): Promise<void> {
if (updates.length === 0) return;
const CHUNK_SIZE = 1000;
const CHUNK_SIZE = 5000;
const chunks = chunkArray(updates, CHUNK_SIZE);
for (const chunk of chunks) {
// Build single bulk UPDATE query using CASE WHEN
const caseStatements: string[] = [];
const params: any[] = [];
// Create a temporary table for this batch
const tempTableName = `temp_posmaster_update_${Date.now()}_${Math.random().toString(36).substring(7)}`;
for (const update of chunk) {
caseStatements.push(`WHEN ? THEN ?`);
params.push(update.id, update.current_holderId);
try {
// Create temporary table
await manager.query(`
CREATE TEMPORARY TABLE ${tempTableName} (
id CHAR(36) PRIMARY KEY,
current_holderId CHAR(36) NULL,
lastUpdateUserId CHAR(36) NOT NULL,
lastUpdateFullName VARCHAR(255) NOT NULL,
lastUpdatedAt DATETIME NOT NULL
) ENGINE=InnoDB
`);
// Build insert query with proper parameter count
const insertParams: any[] = [];
const valuePlaceholders: string[] = [];
for (const u of chunk) {
valuePlaceholders.push('(?, ?, ?, ?, ?)');
insertParams.push(u.id, u.current_holderId, u.lastUpdateUserId, u.lastUpdateFullName, u.lastUpdatedAt);
}
// Bulk insert into temporary table
await manager.query(`
INSERT INTO ${tempTableName} (id, current_holderId, lastUpdateUserId, lastUpdateFullName, lastUpdatedAt)
VALUES ${valuePlaceholders.join(',')}
`, insertParams);
// Update using JOIN with temporary table (very fast - single query per chunk)
await manager.query(`
UPDATE posMaster p
INNER JOIN ${tempTableName} t ON p.id = t.id
SET p.current_holderId = t.current_holderId,
p.next_holderId = NULL,
p.lastUpdateUserId = t.lastUpdateUserId,
p.lastUpdateFullName = t.lastUpdateFullName,
p.lastUpdatedAt = t.lastUpdatedAt
`);
} finally {
// Drop temporary table
await manager.query(`DROP TEMPORARY TABLE IF EXISTS ${tempTableName}`).catch(() => {});
}
// Build IN clause placeholders
const idPlaceholders = chunk.map(() => '?').join(',');
const ids = chunk.map((u: any) => u.id);
// Add common params at the end
params.push(
chunk[0].lastUpdateUserId,
chunk[0].lastUpdateFullName,
chunk[0].lastUpdatedAt,
...ids
);
await manager.query(`
UPDATE posMaster
SET current_holderId = CASE id ${caseStatements.join(' ')} END,
next_holderId = NULL,
lastUpdateUserId = ?,
lastUpdateFullName = ?,
lastUpdatedAt = ?
WHERE id IN (${idPlaceholders})
`, params);
}
}