Reply to Race condition when inserting data / MySQL 4.0+, MyISAM tables

Your name:

Reply:


Posted by Markus on 07/13/07 14:28

Hello

I use a table to cache some informations which need lots of resources to
be composed. The first time the info is needed, it will be composed and
written to the cache table ($db in the example is a PEAR DB object; the
question is the same for other ways of accessing the database):

// Retrieve info if present
$details = $db->getOne("SELECT contents FROM cache WHERE id=".$id." AND
info='details'");
// If not present, compose info and write it to the database
if (!is_string($details) || trim($details) == '') {
$details = $this->compose_details();
$data = array('id' => $id, 'info' => 'details', 'contents' => $details);
$db->query("INSERT INTO cache (id, info, contents) VALUES (".$id.",
'details', '".$details."')");
}

Now I encountered that if several users call a page at the same time
after the cache was flushed, it is possible that between the first line
and the INSERT query the info was entered by another user. This results
in a duplicate key error.

Now I wonder which is the best way to handle this. I see various approaches:
- Use ON DUPLICATE KEY UPDATE (which might fail if MySQL 4.0 is used)
- Try to write some kind of locking mechanism
- Suppress the error message for this special case
- Remove the primary key from the cache table (as it is flushed whenever
items are administrated, duplicate entries might not be a big problem)

Which is the recommended way to handle this? I guess, as MySQL 4.0 and
MyISAM tables are a quite common configuration, there must be some
common practice about this, but I did not find anything by googling...

Thanks for comments!
Markus

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация