MySQL Concurrency Issue FOR UPDATE

34 Views Asked by At

I'm running two call from broweser simultaneously Connection 1 and Connection 2

** Connection 1 :**

$pdo->beginTransaction();
    $selectQuery = "SELECT distributor_type FROM users WHERE id = 1 FOR UPDATE";
    $stmt = $pdo->prepare($selectQuery);
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    $currentBalance = $row['distributor_type'];
    $newBalance = $currentBalance + 100;

    // Simulate delay to exaggerate the race condition
    sleep(20);

    $updateQuery = "UPDATE users SET distributor_type = :newBalance WHERE id = 1";
    $updateStmt = $pdo->prepare($updateQuery);
    $updateStmt->bindParam(':newBalance', $newBalance, PDO::PARAM_INT);
    $updateStmt->execute();

    $pdo->commit();

** Connection 2 :**

    $pdo = new PDO($dsn, $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $selectQuery = "SELECT distributor_type FROM users WHERE id not in (1) FOR UPDATE";
    $stmt = $pdo->prepare($selectQuery);
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    print_r($row);

Why connection 2 is waiting till connection 1 commit or rollback. Although I'm selection other row only

  1. when I'm select with below query is waiting

    SELECT distributor_type FROM users WHERE id not in (1) FOR UPDATE

  2. when I'm select with below query is not waiting

    SELECT distributor_type FROM users WHERE id in (11502,11503,11504) FOR UPDATE

I'm expecting connection 2 should not wait for connection 1 because I'm selection other rows only

0

There are 0 best solutions below