Article #1016: Transaction Based Database Queries

 

A number of related database queries are best placed under a transaction block where an all or none batch of database queries is executed. Applications in which partial database updates would lead to an incomplete, broken link information storage essentially deem systems unusable due to a lack of data integrity. It is crucial that related SQL queries be placed under a transaction block that is committed if and only if all sub-queries are executed successfully, and that the database is unaffected by the failed transaction otherwise.

This precautionary step can be easily overlooked when focus on projects is often placed on demanding deadlines and feature creep. It is at times forgotten or implemented near the last phase of project completion and often without careful thought. Sub-queries may be left out of a complete transaction block or improperly matched with other criteria for rollback depending on the complexity of the process logic.

The real-world example below has been simplified slightly to emphasize the importance of inventory updates. Inventory is the most commonly implemented application in which transactions determine the effectiveness of a computerized system. Product stock (quantities) must be accurately maintained in inventory in conjunction with other system sub components including order entry systems, product pricing models and transaction logs for inventory auditing.

Eg. A product quantity of 300 is placed on an order
Item quantity 300 must be deducted from the inventory table
Item quantity -300 must be inserted into the transaction log table

If an update of 300 items are deducted from the inventory table stock successfully, but an amount of -300 items are not inserted into the transaction log table due to a database failure then a total transaction log inventory count will yield 300 additional items. Therefore the inventory system will report an incorrect count and the inaccuracy will propagate to affect other system components negatively. In this case item stock and backorders will be allocated incorrectly to orders.

If a network connection terminates or internal database failure occurs during script execution, but the transaction rollback or commit statements have not reached execution then the transaction will automatically rollback after the elapsed database timeout period. The database server timeout period further promotes fail-safe transaction execution.

<?

// real-world transaction based queries

function update_inventory ($id)
{
  $link = mssql_connect ("SQLSERVER", "user", "password");
  if (!$link || !mssql_select_db ('dbname', $link))
      die ("Unable to connect or select database!");

  if (!mssql_query ("BEGIN TRANSACTION"))
    return false; // begin all or none update transaction

  // update the existing inventory - adjust stock
  $sql = "UPDATE inventory SET stock = stock + $qty ".
         "WHERE id = '$id'";
  if (!($result = mssql_query ($sql)))
  { // cancel failed transaction
    mssql_query ("ROLLBACK TRANSACTION");
    return false;
  }
  // insert a new inventory transaction log record
  $sql = "INSERT INTO transaction_log (inv_id, $qty) ".
         "VALUES ('$id', '$qty')";
  if (!($result = mssql_query ($sql)))
  { // cancel failed transaction
    mssql_query ("ROLLBACK TRANSACTION");
    return false;
  }

  // commit the successful inventory update transaction
  mssql_query ("COMMIT TRANSACTION");
  return true;
}

// perform database transaction and respond to return value
if (!update_inventory (5)) // update record ID 5
  echo "DB error: Inventory update failed. Try again.";
else
  echo "Inventory successfully updated.";

?>

Code View - dynamicreport.com

 
 

Back to article listing

 


 

Copyright © 2007-2008 Interaxis. All rights reserved.
Contact Webmaster