* Add an operation to the sync queue
(tableName: string, recordId: string, operation: SyncOperation, payload?: any)
| 30 | * Add an operation to the sync queue |
| 31 | */ |
| 32 | enqueue(tableName: string, recordId: string, operation: SyncOperation, payload?: any): void { |
| 33 | // Check if there's already a pending operation for this record |
| 34 | const existing = this.db |
| 35 | .prepare( |
| 36 | `SELECT * FROM sync_queue |
| 37 | WHERE table_name = ? AND record_id = ? AND processed_at IS NULL` |
| 38 | ) |
| 39 | .get(tableName, recordId) as QueueItem | undefined; |
| 40 | |
| 41 | if (existing) { |
| 42 | // Merge operations |
| 43 | const mergedOperation = this.mergeOperations(existing.operation as SyncOperation, operation); |
| 44 | |
| 45 | if (mergedOperation === null) { |
| 46 | // Operations cancel out (e.g., create + delete) |
| 47 | this.db |
| 48 | .prepare('DELETE FROM sync_queue WHERE id = ?') |
| 49 | .run(existing.id); |
| 50 | } else { |
| 51 | // Update existing queue item |
| 52 | this.db |
| 53 | .prepare( |
| 54 | `UPDATE sync_queue |
| 55 | SET operation = ?, payload = ?, attempts = 0, last_error = NULL |
| 56 | WHERE id = ?` |
| 57 | ) |
| 58 | .run(mergedOperation, JSON.stringify(payload), existing.id); |
| 59 | } |
| 60 | } else { |
| 61 | // Add new queue item |
| 62 | this.db |
| 63 | .prepare( |
| 64 | `INSERT INTO sync_queue (table_name, record_id, operation, payload) |
| 65 | VALUES (?, ?, ?, ?)` |
| 66 | ) |
| 67 | .run(tableName, recordId, operation, JSON.stringify(payload)); |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | /** |
| 72 | * Merge two operations on the same record |