3

So, i need to get max number of field called chat_id and after that i need to increment it by one and insert some data in that field, so the query should look something like this:

SELECT MAX(`chat_id`) FROM `messages`;

Lets say it returns me 10 now i need to insert new data

INSERT INTO `messages` SET `chat id` = 11 -- other data here....

So it would work the way i want but my question is what if betwen that time while i'm incrementing and inserting new record other user gonna do the same? than there would already be record with 11 id and it could mess my data is there a way to make sure that the right id goes where i need, btw i can't user auto increment for this.

EDIT as i said i cannot use auto increment because that table already have id field with auto increment, this id is for different porpuse, also it's not unique and it can't be unique

EDIT 2 Solved it by redoing my whole tables structure since no one gave me better ideas

Linas
  • 4,380
  • 17
  • 69
  • 117
  • please see the similar question. http://stackoverflow.com/questions/1587562/problem-with-mysql-insert-max1 – lqez Jan 19 '12 at 17:49
  • After seeing your edits, it sounds like you do not have a separate `chat` table. If not, you should make one. – Jon Jan 19 '12 at 18:17
  • @jon even if i do create seperate table problem would be the same i still can't use auto increment or unique – Linas Jan 19 '12 at 18:22
  • @Linas: You can use `auto_increment` *on the new table* though, which will solve your problem. After the new `id` has been inserted in `chat` you *know* that it is unique, so you can use it as `messages.chat_id` as well without fear of race conditions. – Jon Jan 19 '12 at 18:35

4 Answers4

5

Don't try to do this on your own. You've already identified one of the pitfalls of that approach. I'm not sure why you're saying you can't use auto increment here. That's really the way to go.

CREATE TABLE messages (
    chat_id INT NOT NULL AUTO_INCREMENT,
    ....
)
Joe Stefanelli
  • 132,803
  • 19
  • 237
  • 235
  • I don't want to downplay the good sense in this answer, but the OP explicitly mentions that they **cannot** use auto-increment. – Jon Jan 19 '12 at 17:51
  • @Jon: I saw that and would love to hear OP's reasoning for why they cannot use it. – Joe Stefanelli Jan 19 '12 at 17:53
  • 1
    Me too. But IMHO it would be more appropriate to ask so in a comment before suggesting an explicitly disallowed solution. – Jon Jan 19 '12 at 17:54
3

If you cannot use an auto-increment primary key then you will either have to exclusively lock the table (which is generally not a good idea), or be prepared to encounter failures.

Assuming that the chat_id column is UNIQUE (which it should be from what you 're saying), you can put these two queries inside a loop. If the INSERT succeeds then everything is fine, you can break out of the loop and continue. Otherwise it means that someone else managed to snatch this particular id out of your hands, so repeat the process until successful.

At this point I have to mention that you should not actually use a totally naive approach in production code (e.g. you might want to put an upper limit in how many iterations are possible before you give up) and that this solution will not work well if there is a lot of contention for the database (it will work just fine to ensure that the occasional race does not cause you problems). You should examine your access patterns and load before deciding on this.

Jon
  • 428,835
  • 81
  • 738
  • 806
1

AUTO_INCREMENT would solve this problem. But for other similar situations this would be a great use of transactions. If you're using InnoDb engine you can use transactions to ensure that operations happen in a specific order so that your data stays consistent.

Justin Lucas
  • 2,301
  • 14
  • 22
  • Transactions are not a magic wand that will automatically solve your problems. You have to consider which [transaction isolation level](http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_read-committed) (if any) is suitable. – Jon Jan 19 '12 at 17:53
0

You can solve this by using MySQL's built-in uuid() function to calculate the new primary key value, instead of leaving it to the auto increment feature.

Alter your table to make messages.chat_id a char(36) and remove the AUTO_INCREMENT clause.

Then do this:

# Generate a unique primary key value before inserting.
declare new_id char(36);
select uuid() into new_id;

# Insert the new record.
insert into messages
(chat_id, ...)
values
(new_id, ...);

# Select the new record.
select *
from messages
where chat_id = new_id;

The MySQL's documentation on uuid() says:

A UUID is designed as a number that is globally unique in space and time. Two calls to UUID() are expected to generate two different values, even if these calls are performed on two separate devices not connected to each other.

Meaning it's perfectly safe to use the value generated by uuid as a primary key value.

This way you can predict what the primary key value of the new record will be before you insert it and then query by it knowing for sure that no other process has "stolen" that id from you in between the insert and the select. Which in turn removes the need for a transaction.

Mig82
  • 4,856
  • 4
  • 40
  • 63