Can there be any proper error handling be implemented into a SQL UNIQUE Constraint? So far i'm obviously getting: Error: Duplicate entry 'test1' for key 'username'
But i'd like to have it display a custom comment if possible
You should check in your app code before inserting this
row that no other row exists with the same username.
Then if it exists, show the error you want to the user.
Parsing this unique constraint error
(after you get it) is not a good idea.
So do it before, not after.
Related
I have application that receives multiple requests from external sources (invoices from point-of-sale units). It gets tens of requests per second, and some of those requests are the same (have same request body).
request data is transformed and saved to two associated tables (foreign key). if record already exists (queried by unique composite key), record is updated, otherwise record is added.
the problem is that sometimes if two requests with same body are received at the same time app throws exception that unique key already exists and it can't insert it:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry
It's probably some kind of race condition in MySQL but can't figure it out
Whole process is wrapped in Laravel transaction. I tried setting different isolation levels. SERIALIZABLE resolves that issue but then I get lot of deadlock exceptions, and as I can see sometimes record is not saved at all.
This is simple, what happen here, you have some value declared as "UNIQUE" or "Primary Key" or something like that, and you are trying to insert again, some key restriction it's blocking the insert, this should be good, you avoid duplicate entries in your database, but what you need to do its check if the data what you are trying to insert exist before in the database, not all the columns, you should ask for your keys or key combination, I can not help you more if I don't know the data or the table...
I'm developing an application where users will be importing a few thousand records from a text file. I have a unique constraint on 3 of the columns in my table, but when I attempt to import duplicate records I receive this error.
Error: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '2013-06-01 15:25:41-2013-06-01 15:25:42-null' for key 'start_time'
It looks like CakePHP will stop attempting to insert data once an insert fails due to a constraint violation. Is there any way to simply have CakePHP ignore the constraint violation?
Thank you for your time.
It really depends on how your are importing your data and what RDBMS you are using.
If you are looping line-by-line over the text file and inserting data after each line, you could catch the exception and move on to the next line of your text file. Just remember to push the failed row into some kind of error log, so you'll be able to find which inserts failed. The bigger issue I see is that a thrown Exception might ruin your current transaction, and for mass data insertion you'll definitely want to wrap everything up in a singular transaction for best performance.
If you are using MySQL and CSV files, there's a LOAD DATA INFILE command you could explore using.
The problem is we are importing thousands of records at a time. Checking if a row exists before attempting to insert(I believe this is how CakePHP's unique validation works) will double the amount of queries if I were to try to save it row by row. I'm going to remove the unique constraint on the column and just insert all of the rows. After the new rows are inserted, I'm going to add a unique constraint to those columns and then remove the constraint. I think this will work well in my case because we plan on importing new records only once a month.
I'm currently writing a REST style php server that needs to allow user registration. The basics are working but I am focusing on error handling now. My users table has a unique index on the 'user_name' field and the 'user_email' field. When I try to insert a duplicate value I can read the error and get a string like
Duplicate entry 'noggin182' for key 'user_name'
I need to translate this into something that I can display to the user. Is there is an easy way to get more details of why the insert failed? I could easily parse the string to find out but this feels messy, things would break if the string gets changed in an update or the language changes.
If you're trying to do what I think you're trying to do, it might be worth taking a different approach, and putting the logic for adding a user in to a Stored Procedure, in a single transaction, and doing any checks beforehand to see if the user already exists.
You could then return your own logic as to whether the user added, or a reason why it couldn't be. Or raise your own error or something maybe.
The error message normally contains more information
ERROR 1146 (42S02): Table 'test.no_such_table' doesn't exist
A numeric error code (1146). This number is MySQL-specific and is not portable to other database systems.
You could return this number and display the corresponding text on the client but normally what we do is catch the exception and log the full stacktrace but return only simple text to the client.
Your users don't want to know that there was an attempted duplicate key insert as they can do nothing about that they want to know that the save failed and that the administrator of the site has been alerted to the problem as is looking into it and a solution will be forthcoming..
because of unique key added on that column.
unique does not allow duplicate data.
try this:
$query="select * from table where user_email='".$_POST["user_email"]."'";
$result=mysql_query($query);
if(mysql_num_rows($result)>0)
{
your insert query.....
}
else
{
echo "email already exists";
}
I have a database with a table categories which has a unique key on item_id and user_id. When I'm adding new categories in my controller it using:
$category = new Model_Category();
$category->item_id = $item_id;
$category->user_id = $user_id;
$category->save();
Kohana 3.2 returns a "Duplicate entry '1-3' for key" error. Is it better practice to wrap it in a try/catch or would it be better to check whether the unique key already exists before trying to add it?
I would advice on a try catch, since it uses one less query to check for the duplicate key, however that might limit the amount of information you can display to the user since im not sure if the exception contains the actual column that violates the key, i think its just a generic error so if you want to actually check which of the two columns gives the error you might wanna use a query before that. Hope it helps. FYI i use try catch most of the time, its cleaner and easy to log errors.
I am currently using RedBean for ORM in my models.
I need to insert data into a MySQL table where one of the columns is set to unique.
Currently, data is inserted via a form like so:
//Create
$object = R::dispense('object');
//Need to check if supplied name is a duplicate
$object->name = $name
$object->description = $description
//Save
R::store($object)
Now the problem is that if $name was not duplicated in the database, everything goes well. If it is a duplicate, I can catch the exception and get the SQL error code: 23000
If I echo the exception, I get:
[23000] - SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'abc' for key 'name_UNIQUE'
Another problem is that if I have multiple fields which are set to UNIQUE, the exception will only tell me the first field that's duplicated. Therefore, in order to get the next field, I need to make sure the user corrects the first duplicate and run the query again.
This seems to be quite inefficient. I need to be able to check if the user has inserted duplicate data in multiple fields while not executing too many SQL statements.
What are some best practices for doing this? Also, what's the best practice when it comes to returning whether the action was a success, or if on failure, why and which fields back to the controller?
Thank you :)
You must first perform a "select" to check that the unique entries do not already exist, there is no other way... If you do not want to perform multiple requests from you code, you can implement a stored procedure.
It allows you to perform multiple requests within the same transaction, and that limits the network overhead.
It will also allow you to manage multiple kinds of error (through error codes AFAIR), which will give you a way to identify clearly the problematic field.
Check out this link
Hope that helps !