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.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

General Questions /

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

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

Handling error when having a "Unique" key index


Go to End


2 Posts   2062 Views

Avatar
BP

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;
		}