You are here: Re: Race condition when inserting data / MySQL 4.0+, MyISAM tables « PHP SQL « IT news, forums, messages
Re: Race condition when inserting data / MySQL 4.0+, MyISAM tables

Posted by petersprc on 07/14/07 05:18

With MyISAM, you can do one of the methods you described or use LOCK
TABLES.

In your case I would do ON DUPLICATE KEY UPDATE or remove the unique
constraint on the id.

Finally, if you need to prevent more than one thread from executing
the generate function, you can use a semaphore with the key being your
id.

On Jul 13, 10:28 am, Markus <derernst@NO#SP#AMgmx.ch> wrote:
> 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

 

Navigation:

[Reply to this 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

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