deleteTasksForModelId method

Future<int> deleteTasksForModelId(
  1. String modelType,
  2. String modelId
)

Deletes all pending sync tasks for a specific model type and model ID.

This is useful when an item is deleted locally - we should cancel any pending CREATE/UPDATE operations for that item. Returns the number of tasks deleted.

Implementation

Future<int> deleteTasksForModelId(String modelType, String modelId) async {
  final result = await _db.customUpdate(
    'DELETE FROM sync_queue_items WHERE model_type = ? AND '
    'model_id = ? AND status != ?',
    variables: [
      Variable.withString(modelType),
      Variable.withString(modelId),
      Variable.withString(SyncStatus.dead.name), // Exclude dead tasks
    ],
  );

  // Update model's syncStatus after deletion
  // Since we deleted all non-dead tasks, status is either 'synced' or 'dead'
  if (result > 0) {
    // Check if there are any dead tasks left
    final deadTasks = await _db.customSelect(
      'SELECT COUNT(*) as count FROM sync_queue_items '
      'WHERE model_type = ? AND model_id = ? AND status = ?',
      variables: [
        Variable.withString(modelType),
        Variable.withString(modelId),
        Variable.withString(SyncStatus.dead.name),
      ],
    ).get();

    final hasDeadTasks = (deadTasks.first.data['count'] as int) > 0;
    final syncStatus =
        hasDeadTasks ? SyncStatus.dead.name : SyncStatus.synced.name;
    await updateModelSyncStatus(modelType, modelId, syncStatus);
  }

  return result;
}