import { getDatabase } from "./connection.js"; export interface WorkflowJobCacheRecord { corpId: string; pipelineId: string; jobId: string; flowCode?: string; flowId?: string; executeTime?: number; status?: string; userName?: string; updatedAt?: number; } /** * 按企业 + 工作流 + 单号快速从本地 SQLite 缓存中检索匹配的 Job 记录 */ export function getCachedWorkflowJobByCode( corpId: string, pipelineId: string, flowCode: string, dbPath?: string ): WorkflowJobCacheRecord | null { const db = getDatabase(dbPath); const normalizedCode = flowCode.trim(); const row = db .query( `SELECT corp_id AS corpId, pipeline_id AS pipelineId, job_id AS jobId, flow_code AS flowCode, flow_id AS flowId, execute_time AS executeTime, status, user_name AS userName, updated_at AS updatedAt FROM workflow_job_index WHERE corp_id = ? AND pipeline_id = ? AND (flow_code = ? OR UPPER(flow_code) = UPPER(?)) ORDER BY execute_time DESC, updated_at DESC LIMIT 1` ) .get(corpId, pipelineId, normalizedCode, normalizedCode) as WorkflowJobCacheRecord | null; return row ?? null; } /** * 批量插入或更新 Job 缓存索引 */ export function upsertWorkflowJobIndex( records: WorkflowJobCacheRecord[], dbPath?: string ): void { if (!records.length) return; const db = getDatabase(dbPath); const now = Date.now(); const insertStmt = db.prepare(` INSERT INTO workflow_job_index ( corp_id, pipeline_id, job_id, flow_code, flow_id, execute_time, status, user_name, updated_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(corp_id, pipeline_id, job_id) DO UPDATE SET flow_code = COALESCE(excluded.flow_code, workflow_job_index.flow_code), flow_id = COALESCE(excluded.flow_id, workflow_job_index.flow_id), execute_time = COALESCE(excluded.execute_time, workflow_job_index.execute_time), status = COALESCE(excluded.status, workflow_job_index.status), user_name = COALESCE(excluded.user_name, workflow_job_index.user_name), updated_at = excluded.updated_at `); db.transaction(() => { for (const r of records) { insertStmt.run( r.corpId, r.pipelineId, r.jobId, r.flowCode || null, r.flowId || null, r.executeTime || null, r.status || null, r.userName || null, now ); } })(); }