Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

General Questions /

General questions about getting started with SilverStripe that don't fit in any of the categories above.

Moderators: martimiz, Sean, biapar, Willr, Ingo, swaiba, simon_w

Handling error when having a "Unique" key index


Reply


2 Posts   505 Views

Avatar
Zyzzza

Community Member, 25 Posts

4 March 2013 at 6:16am

Hi All,

Anyone could advise - I've got a Unique index on Dataobject like

static $indexes = array(
"UniqName" => array(
"type" => "unique",
"value" => "`URL`"
)
);

When i try writing a Dataobject with $item->write() it would give me a n error "[User Error] Couldn't run query: UPDATE... " ... Duplicate entry 'http://google.com' for key 2.

I was pinpointed by UncleCheese over the IRC that error handling is :

   public function databaseError($msg, $errorLevel = E_USER_ERROR) {
user_error($msg, $errorLevel);
}

So probably there wont be easy solution like try...catch or smth.

But if you have found a solution for this - please post it here .

PS - I cannot check for duplicates on each write, as there's over 100K records, and doing so would just kill the script .

Avatar
capsula4

Community Member, 4 Posts

20 August 2014 at 11:32am

Edited: 20/08/2014 11:32am

Although is not the cleanest solution, it does the trick when you don't want to perform a verification query.

      ob_start();
      $this->write();
      $error = ob_get_contents();
      ob_end_clean();
      if(empty($error) && strpos($error, 'duplicate key') !== false){
         return true;
      }else{
         return false;
      }