fix(bot): lead race condition — INSERT OR IGNORE + reselect on UNIQUE conflict
- getOrCreateLead: INSERT OR IGNORE prevents UNIQUE constraint race (parallel messages creating same telegram_id lead) - On changes=0, reselect existing lead instead of failing
This commit is contained in:
@@ -47,7 +47,7 @@ export async function getOrCreateLead({ telegramId, username, name }) {
|
||||
}
|
||||
|
||||
const result = await db.runAsync(
|
||||
`INSERT INTO leads (telegram_id, telegram, name, status, verification, custom_fields, created_at, updated_at)
|
||||
`INSERT OR IGNORE INTO leads (telegram_id, telegram, name, status, verification, custom_fields, created_at, updated_at)
|
||||
VALUES (?, ?, ?, 'new', 'pending', '{}', datetime('now'), datetime('now'))`,
|
||||
[
|
||||
tid,
|
||||
@@ -55,6 +55,13 @@ export async function getOrCreateLead({ telegramId, username, name }) {
|
||||
name || null,
|
||||
]
|
||||
);
|
||||
if (result.changes === 0) {
|
||||
// Конфликт: лид создан параллельным запросом — перечитываем
|
||||
const row = await db.getAsync('SELECT id FROM leads WHERE telegram_id = ?', [tid]);
|
||||
if (row) {
|
||||
return { id: row.id, isNew: false };
|
||||
}
|
||||
}
|
||||
logger.info({ telegramId: tid, leadId: result.lastInsertRowid }, 'Lead created from bot interaction');
|
||||
return { id: Number(result.lastInsertRowid), isNew: true };
|
||||
} catch (err) {
|
||||
|
||||
Reference in New Issue
Block a user